使用C++中的fstream时,这个程序有什么问题?

4
下一个程序有什么问题?我希望文件能够到达结尾。
ifstream file("main.cpp", ios::binary | ios::ate);
if (file) {
    //fstream::pos_type size = file.tellg();
    file.seekg(100, fstream::cur);
    if (file.eof()) {
        cout << "eof is true\n";
    }
}

fstream 到达文件末尾时,为什么没有输出 "eof is true"?


好问题,又是另一个案例,表明eof()并不像几乎所有新手认为的那样工作。 - john
1个回答

7

只有在实际读取操作由于到达文件结尾而失败时,eof位才被设置(因此eof()才返回true)。一个寻求操作(显然)不足以满足条件。


但是为什么下一个程序会成为无限循环呢?ifstream file("main.cpp", ios::binary | ios::ate);if (file) { fstream::pos_type size = file.tellg(); long len = 100; file.seekg(0, fstream::beg); while (!file.eof()) { fstream::pos_type rest_size = size - file.tellg(); if (len > rest_size) len = rest_size; char* c = new char[len]; file.read(c, len); delete []c; cout << rest_size << endl; } } - minji_LT
如果您有关于代码的问题,请发表一个新的问题。这个评论中的代码完全无法阅读。但是我在其中看到了while(!file.eof()),这是不好的。http://stackoverflow.com/questions/6512173/ifstream-not-reading-eof-character - Sebastian Redl
@minji_LT 因为在你的程序中eof()从未为true。你的代码存在故障,但并非文件结束故障。 - john

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接