从文件读取时,tellg() 的行为如何?

How does tellg() behave when reading from file?

我正在尝试使用 fstream 从文件中读取。我正在尝试的文件 阅读有这个内容:

1200
1000
980
890
760

我的代码:

#include <fstream>
#include <iostream>

using namespace std;

int main ()
{
    fstream file("highscores.txt", ios::in | ios::out);

    if (!file.is_open())
    {
        cout << "Could not open file!" << endl;
        return 0;
    }

    int cur_score; 

    while (!file.eof())
    {
        file >> cur_score;
        cout << file.tellg() << endl;
    }
}

输出为:

9
14
18
22
26

为什么先读完tellg() returns 9, 首先读取的是数字 (1200),它有 4 个位置 我知道有 \r\n 所以这有 6 个位置。还。如果我在我的文件中添加更多数字 tellg() 将会 return 第一次阅读后数字更大。

如果您使用文本编辑器将文件保存为 UTF8,则文件开头可能会有一个 UTF8 BOM。此 BOM 长度为 3 个字符,因此将其添加到 6 个字符中,将得到 9 个字符。

如果您想确定,请检查文件的开头,其中:

fstream file("highscores.txt", ios::in | ios::out | ios::binary);
if(file) {
    char verify[16];
    file.read(verify, sizeof(verify));
    int rd = file.gcount();
    for(int i = 0; i<rd; i++) {
        cout << hex << setw(2) << (int)verify[i] << " ";
    }
    cout <<dec << endl;
}

编辑:

运行 on windows with MSVC2013 on the file and I found 4, 10, 15, 20, 25 as expected, and I couldn't reproduce your figures.

我现在用 mingw 做了一个测试,在这里我得到了你的数字,奇怪的是增加行数会增加输出。

当您以文本模式阅读 windows(CRLF 行分隔符)文件时,这是 MINGW 的一个错误:

  • 如果我以 UNIX 风格保存文件(即 LF 行分隔符),我会得到相同的程序 4,9,13,17,这又是 [=45= 的预期值] 系统。

  • 如果我以 WINDOWS 样式(即 CRLF 行分隔符)保存文件,并且如果我更改代码以在 ios::binary 中打开文件,我将得到等待4、10、15、20、25。

显然是 old problem