views:

135

answers:

2

I am trying to make my file parsing more robust. Using an ifstream, how can I ensure seekg keeps me in a valid position within the file?

This does not work:

while(m_File.good() && m_File.peek() != EOF)
{ ...a seekg operation moves file position past end of file... }

I assume the current iterator has been pushed way past the end iterator, so the peek() is never true.

+2  A: 

No, there is no way of doing this, short of finding the offset of the end of file and making sure you don't seek beyond it, which causes undefined behaviour - you can of course increase the size of the file by writing.

anon
What is the best way of finding the length of an ifstream?
DanDan
Seeking the end of file :)
Kornel Kisielewicz
It is a shame there is no cleaner way of doing this.
DanDan
+1  A: 

If it's an error when you reach a bad position (e.g. it shouldn't happen) you may try to set the stream exception mask, and catch the appropriate exception outside of the while loop. In that case it'd be the "cleanest" solution.

Kornel Kisielewicz
Seeking beyond the ennd of file is undefined behaviour - there is no exception.
anon
however when reading there is an exception? I'm looking also at this topic : http://stackoverflow.com/questions/1099601/ifstream-seekg-beyond-end-does-not-return-eof-in-vs-2008-express
Kornel Kisielewicz
Yes, a read failure is not UB.
anon