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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7681555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:20:48  来源:igfitidea点击:

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

c++fileiostream

提问by Steffan Harris

I was wondering if there was a way to reset the eof state in C++?

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

回答by Kerrek SB

For a file, you can just seek to any position. For example, to rewind to the beginning:

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

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!

If you already read past the end, you have to reset the error flags with clear()as @Jerry Coffin suggests.

如果你已经读到最后,你必须clear()按照@Jerry Coffin 的建议重置错误标志。

回答by Jerry Coffin

Presumably you mean on an iostream. In this case, the stream's clear()should do the job.

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

回答by user3176017

I agree with the answer above, but ran into this same issue tonight. So I thought I would post some code that's a bit more tutorial and shows the stream position at each step of the process. I probably should have checked here...BEFORE...I spent an hour figuring this out on my own.

我同意上面的答案,但今晚遇到了同样的问题。所以我想我会发布一些更多教程的代码,并在流程的每一步显示流位置。我可能应该在这里检查......之前......我花了一个小时自己解决这个问题。

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) { //...// }