ifstream tellg()没有返回正确的位置

car*_*995 6 c++ fstream file

代码如下:

代码:

#include <iostream>
#include <fstream>

using namespace std;

int main(void)
{
    int id;
    char name[50];
    ifstream myfile("savingaccount.txt");  //open the file
    myfile >> id;
    cout << myfile.tellg(); //return 16? but not 7 or 8
    cout << id ;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

文件内容:

1800567
Ho Rui Jang
21
Female
Malaysian
012-4998192
20 , Lorong 13 , Taman Patani Janam
Melaka
Sungai Dulong

问题 :

1.)我希望tellg()返回7或者8从第一行开始1800567是7位数,所以流指针应该放在这个数字之后和字符串之前"Ho Rui Jang",但是tellg()返回16.为什么会这样?

小智 6

有同样的问题。尝试读取文件流二进制文件:

    ifstream myfile("savingaccount.txt",ios::binary);
Run Code Online (Sandbox Code Playgroud)

对我有帮助


Pet*_*ter 6

这不是编译器错误。 tellg()不保证返回距文件开头的偏移量。有一组最小的保证,例如,如果 from 的返回值tellg()传递给seekg(),文件指针将定位在文件中的相应点。

实际上,在 unix 下,tellg()确实返回距文件开头的偏移量。在 Windows 下,它返回距文件开头的偏移量,但前提是文件以二进制模式打开。

但唯一真正的保证是返回的不同值tellg()将对应于文件中的不同位置。


per*_*ain 5

这似乎更像是编译器错误(可能是gcc)

使用以下代码: -

#include <iostream>
#include <fstream>
using namespace std;
int main(void)
{
    int id;
    char name[50];
    ifstream myfile("savingaccount.txt");  //open the file
    cout << myfile.tellg()<<endl;
    myfile >> id;
    streamoff pos=myfile.tellg();
    cout <<"pos= "<<pos<<'\n';
    cout <<"id= " << id<<'\n' ;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

以下是输出: -

窃听器

在该图像inpstr.exe被从生成Visual studio's clinp.exeg++(gcc version 4.6.1 (tdm-1))

  • 也许应该提出一个bug,让我们看看他们的反应. (4认同)
  • 我在这里坐了5-6个小时试着找出问题所在.我似乎是一个非常执着的类型,我非常专注于解决这个问题,直到我不想在这里问它,直到我起床给自己一杯牛奶.现在问题是由gcc bug引起的 (3认同)
  • @caramel23 你使用的是 Windows 吗?我能够在使用 GCC 4.7.0 的 Windows 上重现这一点,但不能在使用 GCC 4.6.3 的 Ubuntu 上重现。这可能是 Windows 特有的错误。 (2认同)