22

我正在尝试寻找并重新读取数据。但代码失败。

代码是

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;

我的输入测试文件是

qwe

输出是

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

谁能告诉我怎么了?

4

2 回答 2

38

ifs >> str;因为到达文件末尾而结束时,它会设置 eofbit。

在 C++11 之前,seekg()无法从流的末尾寻找(注意:你的实际上是这样,因为输出是Current pos: 0,但这并不完全符合:它应该无法寻找或者它应该清除 eofbit 并寻找)。

无论哪种方式,要解决这个问题,您可以在ifs.clear();之前执行ifs.seekg(pos);

于 2013-05-03T17:22:50.363 回答
6

看起来在读取字符时它会碰到 EOF 并将其标记为流状态。执行 seekg() 调用时流状态不会更改,因此下一次读取检测到 EOF 位已设置并返回而不读取。

于 2013-05-03T17:18:30.510 回答