在C++中重置ifstream对象的文件结束状态

Ste*_*ris 18 c++ iostream file

我想知道是否有办法在C++中重置eof状态?

Ker*_* SB 29

对于文件,您可以寻找任何位置.例如,要回到开头:

std::ifstream infile("hello.txt");

while (infile.read(...)) { /*...*/ } // etc etc

infile.clear();                 // clear fail and eof bits
infile.seekg(0, std::ios::beg); // back to the start!
Run Code Online (Sandbox Code Playgroud)

如果您已经阅读了结尾,则必须使用clear()@Jerry Coffin建议重置错误标记.

  • 我试过这个,只有在``seekg`之前调用`clear`时它才有效.另见:http://cboard.cprogramming.com/cplusplus-programming/134024-so-how-do-i-get-ifstream-start-top-file-again.html (5认同)

Jer*_*fin 5

大概你的意思是在iostream上.在这种情况下,流clear()应该完成工作.