What's wrong with the ifstream seekg

veda picture veda · May 3, 2013 · Viewed 23k times · Source

I am trying to do a seek and re-read the data. but the code fails.

The code is

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;

My input test file is

qwe

The output was

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

Can anyone tell me what's wrong?

Answer

Cubbi picture Cubbi · May 3, 2013

When ifs >> str; ends because the end of file is reached, it sets the eofbit.

Until C++11, seekg() could not seek away from the end of stream (note: yours actually does, since the output is Current pos: 0, but that's not exactly conformant: it should either fail to seek or it should clear the eofbit and seek).

Either way, to work around that, you can execute ifs.clear(); before ifs.seekg(pos);