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

发布于 2024-12-09 00:02:14 字数 33 浏览 0 评论 0原文

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

泪意 2024-12-16 00:02:14

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

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() 重置错误标志。

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.

寂寞清仓 2024-12-16 00:02:14

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

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

十级心震 2024-12-16 00:02:14

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

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

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) { //...// }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文