The problem is related to the text mode, which may convert certain sequences of bytes in the file into a sequence of different size.
Take for example text mode under Windows. Here the byte sequence '\r' '\n'
in a file on the disk is converted at reading time into '\n'
. Now imagine that you have a file:
Hello\r\n
World\r\n
If you position yourself at file.seekg(-1, ios_base::end);
the result is undefined, because it's not clear what the result should be:
- Should you simply be positioned at the
'\n'
? But in this case, reading the file in the reverse order would be inconsistent with reading the file in the correct order.
- Should it be positioned at the
'\r'
, as '\r' '\n'
should be understood as a single byte? But in this case the positioning would have to be done byte by byte, and for every byte the library would have to check the previous one, just in case of.
This is by the way also the reason why you should only directly seekg()
to positions previously acquired by tellg()
.
If you really have to do this kind of positioning from the end, if you open the file as ios::binary
because then you're assured that a byte is always a byte whether counting from the end or counting from the beginning.