2011-10-06 21 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

私はこれを試しました。これは、 'clear'が* see *' seekg'の前に呼び出された場合にのみ機能します。こちらもご覧ください:http://cboard.cprogramming.com/cplusplus-programming/134024-so-how-do-i-get-ifstream-start-top-file-again.html – Frank

+0

@フランク:ありがとう、編集済み。私はあなたが失敗したストリームでは全く動作できないと思います。 –

+0

後半の読者の場合:[cppリファレンス](http://en.cppreference.com/w/cpp/io/basic_istream/seekg)によると、C++ 11以降は削除する必要はありません。 – Aconcagua

4

おそらくiostreamを意味します。この場合、ストリームのclear()が処理を行う必要があります。

2

私は上記の答えに同意しますが、今夜同じ問題に遭遇しました。だから私はもう少しチュートリアルで、プロセスの各段階でストリームの位置を示すコードをいくつか投稿すると思った。私はおそらくここにチェックしておくべきだった...前に...私は1時間を自分で考え出した。

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) { //...// } 
関連する問題