【发布时间】:2011-12-02 15:38:58
【问题描述】:
我想知道是否有办法在 C++ 中重置 eof 状态?
【问题讨论】:
我想知道是否有办法在 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!
如果您已经阅读到最后,则必须按照@Jerry Coffin 的建议使用clear() 重置错误标志。
【讨论】:
clear被调用之前 seekg时才有效。另请参阅:cboard.cprogramming.com/cplusplus-programming/…
大概您的意思是在 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) { //...// }
【讨论】: