0

This is my code below.

Here the output is (Hi 5). If I remove the third line(use to) output is (Hi 4). Technically output should be (Hi 3) but tellg() is increasing with every increase in line.

#include<bits/stdc++.h>
void main(){
fstream file("d.txt",ios::trunc | ios::in | ios::out);
string c;
file<<"Hi there"<<endl;
file<<"good evil"<<endl;
file<<"use to"<<endl;
file.seekg(0,ios::beg);
file>>c;
cout<<c<<" "<<file.tellg()<<endl;
}
halfer
  • 19,824
  • 17
  • 99
  • 186
  • you should probably add `using namespace std;` and change `void main()` to `int main()` because otherwise it doesn't compile. Besides that, I get `Hi 2` as output no matter how many line I enter. What operating system and compiler are you on? – Leonid Apr 05 '20 at 13:24
  • @Leonid I am on windows and i have compiled the code with my terminal. I got an o/p of Hi 5 – Hemang Shrimali Apr 06 '20 at 20:53
  • tellg() has no meaningful value for text files. The stream needs to read ahead to deal with multi-byte encodings and line ending quirks. Ideally it would hide those quirks, but ideals are hard to come by in iostream land. Only use it for ios::binary files. Or not at all, a common conclusion. – Hans Passant Apr 06 '20 at 22:04

1 Answers1

0

The standard actually doesn't guarantee any specific value for tellg, only that if seekg is run sometime afterwards on its output, it will put the stream into the same place that it was. In any case, the output of tellg is implementation-defined. It doesn't even have to be convertible to an integral type. In terms of implementations, generally files opened in binary mode (and in text mode for *nix systems) will produce tellg output equal to the byte offset from the beginning of the file, while in text mode (non-*nix systems) producing some value greater or equal to the byte offset.

For a specific reason why tellg was increasing by 1 each time you added a line, one possible factor that may have influenced this implementation-defined behaviour in your compiler might be the fact that the Windows line terminator \n\r is two bytes instead of one. Of course, relying on implementation-defined behaviour is generally a bad idea.

Source: https://stackoverflow.com/a/22986486

Leonid
  • 708
  • 5
  • 12