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

Resetting the End of file state of a ifstream object in C++

本文关键字:文件 结束 状态 对象 ifstream c++      更新时间:2023-10-16

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

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

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!

如果你已经读过了结尾,你必须重置错误标志与clear() @Jerry Coffin建议。

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

我同意上面的答案,但今晚遇到了同样的问题。所以我认为我应该发布一些代码,这是一个教程,并显示流程的每个步骤的流位置。我可能应该在这里检查一下……我花了一个小时自己想出来的。

ifstream ifs("alpha.dat");       //open a file
if(!ifs) throw runtime_error("unable to open table file");
while(getline(ifs, line)){
         //......///
}
//reset the stream for another pass
int pos = ifs.tellg();
cout<<"pos is: "<<pos<<endl;     //pos is: -1  tellg() failed because the stream failed
ifs.clear();
pos = ifs.tellg();
cout<<"pos is: "<<pos<<endl;      //pos is: 7742'ish (aka the end of the file)
ifs.seekg(0);
pos = ifs.tellg();               
cout<<"pos is: "<<pos<<endl;     //pos is: 0 and ready for action
//stream is ready for another pass
while(getline(ifs, line) { //...// }