Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ifstream tellg() not returning the correct position

Tags:

c++

file

fstream

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?

like image 896
caramel1995 Avatar asked Sep 03 '12 17:09

caramel1995


1 Answers

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.

like image 170
Peter Avatar answered Oct 22 '22 21:10

Peter