[英]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) { //...// }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.