samedi 25 avril 2015

Why I have to give a negative two offset for seekg for end of file


So I was reading about file handling and wanted to read a text file from the end. So I decided to seek the get pointer to the last character using,

seekg(-2,ios::end);

My complete code is:

fin.open("source.txt");
fin.seekg(-2,ios::end);

fin>>ch;
if(fin.fail())
    cout<<"uh oh!";
else
    cout<<ch;

My question is that why I have to make the offset -2 and not -1 as I assume that the ios::end places the get pointer to one position after the last valid character of the file.

Any help? Thanks.


Aucun commentaire:

Enregistrer un commentaire