2011-10-06 9 views

Respuesta

22

Para un archivo, puede simplemente buscar cualquier posición. Por ejemplo, para rebobinar hasta el principio:

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! 

Si ya leer más allá del final, tiene que restablecer los indicadores de error con clear() como @Jerry Ataúd sugiere.

+4

Intenté esto, y solo funciona si se llama 'clear' * before *' seekg'. Consulte también aquí: http://cboard.cprogramming.com/cplusplus-programming/134024-so-how-do-i-get-ifstream-start-top-file-again.html – Frank

+0

@Frank: gracias, editado. Supongo que no puedes operar en una secuencia fallida, lo cual tiene sentido. –

+0

Para lectores tardíos: Según [cpp reference] (http://en.cppreference.com/w/cpp/io/basic_istream/seekg), la eliminación ya no es necesaria ya que C++ 11 ... – Aconcagua

4

Posiblemente se refiere a un iostream. En este caso, la corriente clear() debería hacer el trabajo.

2

Estoy de acuerdo con la respuesta anterior, pero me encontré con este mismo problema esta noche. Así que pensé en publicar un código que es un poco más tutorial y muestra la posición del flujo en cada paso del proceso. Probablemente debería haber comprobado aquí ... ANTES ... Pasé una hora averiguando esto por mi cuenta.

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