【问题标题】:What's wrong with the ifstream seekgifstream seekg 有什么问题
【发布时间】:2013-04-28 04:12:23
【问题描述】:

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

代码是

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

谁能告诉我怎么了?

【问题讨论】:

标签: c++ ifstream seekg


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

    • 尽管 C++ 标准 (n3337 §27.7.2.3.41) 说“效果:表现为未格式化的输入函数(如 27.7.2.3,第 1 段所述),但函数首先清除eofbit...",其实还是需要手动调用clear(),很奇怪。
    • @Gavin 我观察到了类似的行为。然而,事实证明,当使用read 读取文件的字节数时,没有设置 eof 位。一旦您请求的字节比文件包含的多一个字节,both 都会设置故障位和 eofbit,但自 C++11 以来只有 seekg 的 eofbit will be cleared
    猜你喜欢
    • 1970-01-01
    • 2013-12-28
    • 1970-01-01
    • 2013-12-28
    • 2012-03-10
    • 2011-06-09
    • 1970-01-01
    • 1970-01-01
    • 2010-11-08
    相关资源
    最近更新 更多