Ifstream tellg () does not return the correct position

The code is as follows:

The code:

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

File contents:

  1800567
 Ho rui jang
 21
 Female
 Malaysian
 012-4998192
 20, Lorong 13, Taman Patani Janam
 Melaka
 Sungai dulong

Problem:

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

+6
source share
3 answers

This is more like a compiler error (possibly 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; } 

The following is the conclusion: -

Bug

In the image, inpstr.exe was created from Visual studio cl , and inp.exe from g++(gcc version 4.6.1 (tdm-1))

+5
source

had the same problem. try reading the binary:

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

it helps me

+3
source

This is not a compiler error. tellg() not guaranteed to return an offset from the beginning of the file. There is a minimal set of guarantees, such as if the return value from tellg() is passed to seekg() , the file pointer will be located at the corresponding point in the file.

In practice, unix tellg() returns the offset from the beginning of the file. In windows, it returns the 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.

0
source

Source: https://habr.com/ru/post/924466/


All Articles