ifstream tellg() not returning the correct position

11,226

Solution 1

This seems more like a compiler bug (probably gcc)

With the following Code:-

#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;
}

Following is the output:-

Bug

In the image inpstr.exe was generated from Visual studio's cl while inp.exe from g++(gcc version 4.6.1 (tdm-1))

Solution 2

had the same issue. try to read the filestream binary:

    ifstream myfile("savingaccount.txt",ios::binary);

it helped for me

Solution 3

It is not a compiler bug. tellg() is not guaranteed to return an offset from the start of the file. There are a minimal set of guarantees such as, if the return value from tellg() is passed to seekg(), the file pointer will position at the corresponding point in the file.

In practice, under unix, tellg() does return an offset from the start of the file. Under windows, it returns an offset from the beginning of the file but only if the file is opened in binary mode.

But the only real guarantee is that different values returned from tellg() will correspond to different positions in the file.

Share:
11,226

Related videos on Youtube

caramel1995
Author by

caramel1995

Updated on July 14, 2022

Comments

  • caramel1995
    caramel1995 almost 2 years

    read.cpp

    #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;
    }
    

    savingaccount.txt

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

    The Problem

    I expect the tellg() to either return 7 or 8 since the first line 1800567 which is 7 digits so the stream pointer should be placed after this number and before the string "Ho Rui Jang", but tellg() returns 16. Why is it so?

    • lccarrasco
      lccarrasco over 11 years
      Is the file saved with a special encoding? with ANSI encoding it seems to work fine (reports 7) on Visual Studio 2010
  • GLCraft
    GLCraft over 7 years
    It did for me too. I think that if the file is UTF-8 without setting binary flag, ifstream load a "é" as only one character, whereas it takes two.
  • jtbr
    jtbr over 6 years
    When I save a pos with tellg() and set it again with seekg(), it goes to another position slightly later in the file. (win7 mingw gcc 5.3.0).