The class template std::basic_filebuf
holds a single file position
§ 27.9.1.1
- The class basic_filebuf associates both the input sequence and the output sequence with a file.
- The restrictions on reading and writing a sequence controlled by an object of class basic_filebuf are the same as for reading and writing with the Standard C library FILEs.
- In particular:
- If the file is not open for reading the input sequence cannot be read.
- If the file is not open for writing the output sequence cannot be written.
- A joint file position is maintained for both the input sequence and the output sequence.
What this means is that when you use a std::basic_fstream
, which by default uses a std::basic_filebuf
, the single file position is moved by both seekp()
and seekg()
; unless you use a separate variable to store one of the positions so you can then seek back to it, you cannot keep track of put and get positions independently.
The implications of point 2 are that between reads and writes on an fstream
you must either flush the buffer or seek the file position when changing from output to input, and you must either be at the end of the file or seek the file position when changing from input to output.
For detail on these restrictions, see section 7.19.5.3/7 of the C99 standard ("The fopen
function"), or 7.21.5.3/7 of C11.