2011-10-06 31 views

回答

22

對於一個文件,你可以尋求到任何位置。例如,要繞回到開頭:

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棺材建議將錯誤標誌與clear()復位。

+4

我試過了,只有*'seekg'之前調用'clear'時它纔有效。另見這裏:http://cboard.cprogramming.com/cplusplus-programming/134024-so-how-do-i-get-ifstream-start-top-file-again.html – Frank

+0

@Frank:謝謝,編輯。我想你根本無法在一個失敗的流上操作,這是有道理的。 –

+0

對於較晚的讀者:根據[cpp參考](http://en.cppreference.com/w/cpp/io/basic_istream/seekg),自C++ 11以來不再需要清除... – Aconcagua

4

想必你的意思上的iostream。在這種情況下,流clear()應該完成這項工作。

2

我的答案同意之上,但遇到了同樣的問題在今晚。所以我想我會發布一些代碼,這是一個更多的教程,並顯示流程的每一步的流位置。我可能應該在這裏檢查......在......之前,我花了一個小時來自己解決這個問題。

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