2013-05-03 9 views
13

Sto cercando di cercare e rileggere i dati. ma il codice fallisce.Cosa c'è che non va nella ricerca ifstream

Il codice è

std::ifstream ifs (filename.c_str(), std::ifstream::in | std::ifstream::binary); 

std::streampos pos = ifs.tellg(); 

std::cout <<" Current pos: " << pos << std::endl; 

// read the string 
std::string str; 
ifs >> str; 

std::cout << "str: " << str << std::endl; 
std::cout <<" Current pos: " <<ifs.tellg() << std::endl; 

// seek to the old position 
ifs.seekg(pos); 

std::cout <<" Current pos: " <<ifs.tellg() << std::endl; 

// re-read the string 
std::string str2; 
ifs >> str2; 

std::cout << "str2: (" << str2.size() << ") " << str2 << std::endl; 
std::cout <<" Current pos: " <<ifs.tellg() << std::endl; 

mio file di test di ingresso è

qwe 

L'uscita era

Current pos: 0 
str: qwe 
Current pos: 3 
Current pos: 0 
str2: (0) 
Current pos: -1 

Qualcuno mi dica cosa c'è di sbagliato?

+0

possibile duplicato del [seekg() funzione fallisce] (http://stackoverflow.com/questions/11264764/seekg-function-fails) – amo

risposta

5

Sembra leggendo i caratteri che sta colpendo l'EOF e contrassegnandolo nello stato del flusso. Lo stato del flusso non viene modificato quando si effettua la chiamata seekg() e quindi la lettura successiva rileva che il bit EOF è impostato e restituisce senza leggere.

+5

La soluzione è chiamare 'ifs.clear()'. –

27

Quando ifs >> str; termina perché viene raggiunta la fine del file, imposta l'eofbit.

Fino C++ 11, seekg() non poteva chiedere di distanza dalla fine del flusso (nota: la vostra realtà fa, dal momento che l'uscita è Current pos: 0, ma che non è esattamente conforme: si dovrebbe o non riuscire a cercare o dovrebbe cancellare il eofbit e cerca).

In entrambi i casi, per aggirare questo, è possibile eseguire ifs.clear(); prima ifs.seekg(pos);

Problemi correlati