Why does ifstream set the failbit to 1 after reading the last line of the specified file? How do I know if the specified file has been read correctly?
bool read_csv_file(const char* filename, vector<string>& lines, bool adding = false)
{
if( !adding ) lines.clear();
ifstream csvfile;
csvfile.open(filename);
if( csvfile.is_open() )
{
string line;
while( csvfile.good() && getline(csvfile,line) )
{
lines.push_back(line);
cout << "fail: " << csvfile.fail() << endl;
}
cout << "fail: " << csvfile.fail() << endl;
csvfile.close();
return (!csvfile.fail());
}
return false;
}
The only reason
failbitcould be set after reading the lastline (or any line) is if there were an error in the library, and
I don’t really believe it. If
failbitis set, it means thatyou didn’t read anything. In your case, it will never be set
when you’re in the loop; if it were set,
getlinewould haveevaluated to
false, and you wouldn’t have entered the loop.And of course, the loop terminates precisely because
getlinefails (or would fail—normally, you would not test for
goodbefore doing input, and if you do, consider that thefailbitwas set, regardless, if the test fails).The usual pattern for this sort of thing is:
When
someInputisstd::getline(), however, you will neverfail because of a formatting error, so the
else ifabove willnever be true (and a lot of code treats hard disk errors as if
they were an end of file, and so ignores the
ifpart as well).