ifstream seekg有什么问题

ved*_*eda 17 c++ ifstream seekg

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

代码是

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;
Run Code Online (Sandbox Code Playgroud)

我的输入测试文件是

qwe
Run Code Online (Sandbox Code Playgroud)

输出是

 Current pos:  0
str: qwe
 Current pos:  3
 Current pos:  0
str2: (0)
 Current pos:  -1
Run Code Online (Sandbox Code Playgroud)

谁能告诉我什么是错的?

Cub*_*bbi 32

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

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

无论哪种方式,要解决的是,你可以执行ifs.clear();ifs.seekg(pos);

  • 即使 C++ 标准 (n3337 §27.7.2.3.41) 说“效果:表现为无格式输入函数(如 27.7.2.3,第 1 段所述),但该函数首先清除 eofbit ......”,实际上,我们仍然需要手动调用`clear()`,这很奇怪。 (2认同)

div*_*a23 6

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