C++ ifstream seekg 有什么问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16364301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 20:17:48  来源:igfitidea点击:

What's wrong with the ifstream seekg

c++ifstreamseekg

提问by veda

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?

谁能告诉我出了什么问题?

回答by Cubbi

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

ifs >> str;因为到达文件末尾而结束时,它设置 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).

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

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

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

回答by diverscuba23

It looks like in reading the characters it is hitting the EOF and marking that in the stream state. The stream state is not changed when doing the seekg() call and so the next read detectes that the EOF bit is set and returns without reading.

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