Search code examples
c++iostreamstandard-libraryseek

seekg and seekp : difference between seek(streampos pos) and seek(streamoff off, ios::beg)


If we look to the documentation of istream and ostream, we have the following functions :

istream& seekg ( streampos pos );
istream& seekg ( streamoff off, ios_base::seekdir dir );

ostream& seekp ( streampos pos );
ostream& seekp ( streamoff off, ios_base::seekdir dir );

I wonder why there are two form of the functions each time, and not just :

istream& seekg ( streamoff off, ios_base::seekdir dir = ios_base::beg );
ostream& seekp ( streamoff off, ios_base::seekdir dir = ios_base::beg );

What would be the difference between having these two functions instead of the standard four ones ?


Solution

  • streampos is a typedef for std::fpos<std::char_traits<char>::state_type> which holds the current position in the stream and also the current shift state . Multi-byte encoding schemes such as shift-jis have a state-dependent encoding. What this means basically is that depending on the previous sequence of characters, how you interpret a certain byte in a stream can be different. With streampos you not only hold a position in the stream, but the shift-state at that point in the stream is also stored. Also, because newlines, etc. are interpreted differently on different systems, so logical position in a text file could be different from it's actual physical position. These are some of the reasons why streampos cannot be a simple integer type.