fstream seekg(), seekp(), and write()

百般思念 提交于 2019-11-28 08:15:32
user657267

The class template std::basic_filebuf holds a single file position

§ 27.9.1.1

  1. The class basic_filebuf associates both the input sequence and the output sequence with a file.
  2. 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.
  3. 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!