【问题标题】:C++: file.seekg() does not appear to return current locationC++:file.seekg() 似乎没有返回当前位置
【发布时间】:2015-02-28 19:12:10
【问题描述】:

我正在尝试备份 ifstream 中的一行。 file.tellg() 正在返回一个我没想到的值。在下面的示例中,在读取第一行(长度为 15 个字符的字符串)后,我希望 file.tellg() 返回 16。相反,它返回 41。有人可以提供一些关于这种行为的见解吗?

test.cpp

#include <fstream>
#include <ios>
#include <string>
#include <iostream>
using namespace std;

int main(){
    ifstream file("sample.ics", ios::in);

    string line;
    string key0;
    string key1;
    string value0;
    string value1;

    getline(file, line, '\n');

    cout << "line = " << line << endl;
    cout << "line.length = " << line.length() << endl; // should be 15;

    cout << "Attempt:" << endl;
    int pos = file.tellg(); // should be 16;
    cout << "  pos = " << pos << endl;

    getline(file, key0, ':');
    getline(file, value0, '\n');

    cout << "  First:" << endl;
    cout << "    " << key0 << ":" << value0 << endl;

    cout << "  backing up..." << endl;
    file.seekg(pos, ios_base::beg);

    getline(file, key1, ':');
    getline(file, value1, '\n');

    cout << "  Second:" << endl;
    cout << "    " << key1 << ":" << value1 << endl;

    file.close();
}

输出:

line = BEGIN:VCALENDAR
line.length = 15
Attempt:
  pos = 41
  First:
    CALSCALE:GREGORIAN
  backing up...
  Second:
    ION:2.0

sample.ics

BEGIN:VCALENDAR
CALSCALE:GREGORIAN
VERSION:2.0
METHOD:PUBLISH
...

【问题讨论】:

  • std::istream::tellg() 不返回int,而是返回std::streampos:您是否尝试使用此类型恢复位置?
  • 我试过上面的代码。在我的电脑上是pos = 16
  • 可能是行尾兼容性问题。请参阅thisthisthis
  • streampos 仍然是 41。同样的结果发生

标签: c++ c++11 fstream seekg


【解决方案1】:

尝试以二进制模式打开文件,看看是否得到相同的结果:

ifstream 文件("sample.ics", ios::binary);

【讨论】:

  • 以二进制模式打开可能会导致将文件作为文本读取,但
  • 没关系。你必须使用 std::streampos 而不是 int
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-30
  • 2015-05-30
  • 2017-04-25
  • 1970-01-01
  • 1970-01-01
  • 2018-05-16
相关资源
最近更新 更多