2011-10-06 75 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) { //...// }