ifstream seekg 有什么问题

What's wrong with the ifstream seekg

本文关键字:问题 什么 seekg ifstream      更新时间:2023-10-16

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

代码

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
谁能告诉我怎么了?

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

直到c++ 11, seekg()不能从流的末尾寻找(注意:你的实际上可以,因为输出是Current pos: 0,但这不是完全一致的:它应该失败查找或者它应该清除eofbit并查找)。

无论如何,要解决这个问题,您可以在ifs.seekg(pos);

之前执行ifs.clear();

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