0

I want to read all lines from a file, line by line with a fstream variable.

For example:

#include <fstream>

fstream fsFile;

fsfile.open("file.txt", ios::in);

while (fsFile.getline(szLine, LINE_SIZE + 1))
{
    cout << szLine << endl;
}

When I want to read all the lines but I got a line that is bigger than LINE_SIZE the fsFile.bad() returns true and I get it.
But, I want to know how is it that fsFile.getline(szLine, LINE_SIZE + 1) suddenly returns false?
I mean what is the return value of the function?
If its null and I think it is why is it null?
And when it is not null what it returns?
Thank you for your support.

mortalis
  • 2,060
  • 24
  • 34

1 Answers1

2

Use the std::string version of getline:

std::ifstream fsFile("file.txt");
std::string line;
while(std::getline(fsFile, line)) {
    std::cout << line << '\n';
}

getline (both versions) returns a reference to the stream, which is convertible to bool so you can check it's state (if the read failed, typically because we hit the end of the file).

This version of getline is definitely preferable, because by using a std::string you completely stop worrying about the memory buffer. No need to create it yourself and remember to destroy it, no need to worry about the size of the line.


Also, please reconsider your use of what are often considered bad practices: using namespace std; and endl.

Community
  • 1
  • 1
BoBTFish
  • 19,167
  • 3
  • 49
  • 76