0

i am kinda new to programming and here is my question. I need to do a text editor(something like microsoft notepad but more simple). Im trying to do it step by step like first i need to open file, then read it and etc. But this code clears my programme and i cant properly understand how do i read it line by line(probably using for or while). Thanks

  #include <iostream>
#include <fstream>

using namespace std;

/*
void openFile()
{
    ofstream file2("text2.txt"); // create and open text file
    file2 << "Hello there"; // write in file
    file2.close(); // close file
}
*/

void readFile(char text[4050])
{

    ifstream file("text2.txt"); // read from file
    if (!file.is_open()) // if file is not opened then write "file is not found". else
        cout << "File is not found!" << endl;
    else
    {
        file.getline(text, 4050); // to where(text), max symbols(4050)
        cout << text << endl;
        file.close();
    }
}

using namespace std;

int main()
{

    char text[4050];

    ofstream file2("text2.txt");
    readFile(text);
    return 0;
}

My code is probably wrong and weird but i'll try my best to fix it once i figure it out how.

AlexMIEL
  • 43
  • 1
  • 7
  • How did you chose 4050 as the max number of symbols ? I'd recommend using `string` instead of `char[]` as you are in c++, or at least use a `#define MAX_CHARS 4050` and use `MAX_CHARS` instead of 4050 everywhere in your code, so if you need to change that value you won't have to seek for every occurence of 4050. – Rafalon Apr 13 '17 at 10:58
  • Yes indeed. Thanks sir. By the way i just picked a random number that i felt would be enough for me, but yeah string is better. thanks – AlexMIEL Apr 13 '17 at 11:05

1 Answers1

2

Here is the simplest way to read a file line by line.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
  string line;
  ifstream myfile ("MyFile.txt");
  if (myfile.is_open()) {
    while ( getline (myfile,line) ) {
      cout << line << '\n';
    }
    myfile.close();
  }
  else {
    cout << "Unable to open file"; 
  }
  return 0;
}
ShahzadIftikhar
  • 302
  • 1
  • 8
  • Thanks a lot! It works! But can you please explain me 1 thing as long as its not a trouble for you? I mean the "while(...)" thing. – AlexMIEL Apr 13 '17 at 11:04
  • A `while` loop statement repeatedly executes a target statement ( written in while brackets ) as long as a given condition is true. In this case `getline (myfile,line)` will return false when there is no more line in the file and the loop will terminate. – ShahzadIftikhar Apr 13 '17 at 11:08