I read a question on Stack Overflow where the eofbit for the istream file
is set but the failbit is not. In that case file is true and file.eof() is true but file.good() is false. For example with a file exactly one byte in size:
ifstream file("one.txt");
assert( file.is_open() );
for( int i = 0; i < 2; ++i )
{
char chars[255] = {0};
file.getline(chars, 2);
//file.read( chars, 2 );
cout << "file: " << !!file << endl;
cout << "good: " << file.good() << endl;
cout << "eof: " << file.eof() << endl;
cout << "fail: " << file.fail() << endl;
cout << "bad: " << file.bad() << endl;
cout << endl;
}
This is the output:
file: 1
good: 0
eof: 1
fail: 0
bad: 0
file: 0
good: 0
eof: 1
fail: 1
bad: 0
If I comment out the getline() and use read() instead, I get this:
file: 0
good: 0
eof: 1
fail: 1
bad: 0
file: 0
good: 0
eof: 1
fail: 1
bad: 0
In both cases I'm reading past the end of the file in the loop's first iteration. Why is one EOF and fail and one isn't? The answer in the other thread says "whenever you encounter the end of a file without attempting to read behind it." read behind it? What does that mean?