在c++中重置ifstream对象的文件结束状态
Resetting the End of file state of a ifstream object in C++
我想知道是否有办法在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) { //...// }
相关文章:
- 通过终端在文件中输入时检测EOF(文件结束)时出现问题
- 带有文件结束函数的 while 循环重复输出文件中的最后一个数字两次
- 触发文件结束的原因
- 从 ifstream 读取,直到文件结束
- C++:读取.BMP文件时出现问题;文件结束时间早于预期
- C 功能:读取直到文件结束 - 查找代码中的错误
- C :在文件结束时GetLine冻结
- 表示文件结束
- 如何让程序知道当我使用 while(cin>> 时文件结束
- 文件结束输入不起作用
- 使用RAII写入文件结束标记
- 在文件结束后继续输入
- .hpp 文件上的意外文件结束错误
- 读取:ASIO中的文件结束.插座为什么要关上
- 防止包括从hxx(模板定义)文件结束头
- fstream对象的文件结束
- 文件不会重复自己,直到文件结束
- 文件结束检查不起作用 (C++)
- 语法错误,意外的标记,期望文件结束
- 如何模拟文件结束