c++ - Why I have to give a negative two offset for seekg for end of file -
so reading file handling , wanted read text file end. decided seek pointer 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 why have make offset -2 , not -1 assume ios::end
places pointer 1 position after last valid character of file.
any help? thanks.
the reason of error use >>
, have last character '\n'
or space.
seeking -1 positions on '\n', ignored extractor >>
(it skips whitespaces , '\n'). if position 1 character before, -2, on last non space character , works.
to see what's going on @ end of file:
in.open("source.txt"); fin.seekg(-1,ios::end); // -1 last char of file ch = fin.get(); // read 1 character without ignoring if(fin.fail()) cout<<"uh oh!"; else cout<<(int)ch <<"="<<ch<<endl; // display char code (if not printable) , char
Comments
Post a Comment