Akash Kabir Akash Kabir - 3 months ago 10
C++ Question

showing -1 while getting the position of get_pointer

#include<fstream>
#include<iostream>
using namespace std;
int main()
{ ifstream fin;
fin.open("pro.txt");
char ch;
while(!fin.eof())
{
fin.get(ch);
cout<<ch;
}
fin.seekg(0);
int pos=(int)fin.tellg();
cout<<"\n pointer is at :"<<pos;
fin.close();
return 0;
}


content of file pro.txt

this is the test file text


even after fin.seek(0) the position of get_pointer returned by fin.tellg() is always -1 (WHY ?). it happens only when i read the file till the eof(). HELP

output

this is the test file text
pointer is at: -1

Answer

From documentation:

C++98: If the eofbit flag is set before the call, the function fails (sets failbit and returns).

If you do fin.clear() before seekg, it will work.