【发布时间】:2014-02-26 03:55:52
【问题描述】:
我在 Stack Overflow 上读到了 question,其中设置了 istream file 的 eofbit,但未设置故障位。在这种情况下,file 为 true,file.eof() 为 true,但 file.good() 为 false。例如,文件大小正好是一个字节:
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;
}
这是输出:
file: 1
good: 0
eof: 1
fail: 0
bad: 0
file: 0
good: 0
eof: 1
fail: 1
bad: 0
如果我注释掉 getline() 并改用 read(),我会得到:
file: 0
good: 0
eof: 1
fail: 1
bad: 0
file: 0
good: 0
eof: 1
fail: 1
bad: 0
在这两种情况下,我都在循环的第一次迭代中读取文件末尾。为什么一个 EOF 和失败而一个不是?另一个线程中的答案是“每当您遇到文件末尾而不尝试在其后面读取时”。后面读了吗?这是什么意思?
【问题讨论】: