C++:file.seekg() 似乎没有返回当前位置

标签 c++ c++11 fstream seekg

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

测试.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

示例.ics

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

最佳答案

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

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

关于C++:file.seekg() 似乎没有返回当前位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28785722/

相关文章:

c++ - 无法读取整个文件

c++ - 2D openGL 引擎简单光源和帧缓冲区 (c++)

c++ - 如何在字符串 vector 中引用字符串的特定字符?

C++11 std::async 回调

c++ - 为什么我的 C++ 磁盘写入测试比使用 bash 的简单文件复制慢得多?

c++ - 使用 fstream 读取

c++ - 我可以将 Visual Studio 2005 设置为在调试时忽略特定代码区域中的断言吗

C++/CLI 引发另一个对象的事件

c++ - 如何避免丢失自动生成的初始化列表构造函数?

c++ - 如何检测一个方法是否是虚拟的?