问题
I would like to know in what case we can have :
bool(std::ifstream) != std::ifstream::good()
The difference is that bool(std::ifstream)
does not test the eof
bit whereas std::ifstream::good()
tests it. But practically, the eof
bit is raised if one try to read something after the end of the file. But as soon as you try to do this I think that either fail
or bad
bit is also set.
Consequently in what case you can only raise the eof
bit ?
回答1:
Simply put, whenever you encounter the end of a file without attempting to read behind it. Consider a file "one.txt" which contains exactly one single '1' character.
Example for unformatted input:
#include <iostream>
#include <fstream>
int main()
{
using namespace std;
char chars[255] = {0};
ifstream f("one.txt");
f.getline(chars, 250, 'x');
cout << f.good() << " != " << bool(f) << endl;
return 0;
}
0 != 1
Press any key to continue . . .
Example for formatted input:
#include <iostream>
#include <fstream>
int main()
{
using namespace std;
ifstream f("one.txt");
int i; f >> i;
cout << f.good() << " != " << bool(f) << endl;
return 0;
}
0 != 1
Press any key to continue . . .
来源:https://stackoverflow.com/questions/16555371/in-what-practical-case-boolstdifstream-stdifstreamgood