Reading and writing to the same file using the same fstream

后端 未结 2 1976
粉色の甜心
粉色の甜心 2020-11-27 06:38

I have a file that already contains some data (say, 8 kB). I want to read something from the beginning of the file, and then overwrite data starting where I finished reading

相关标签:
2条回答
  • 2020-11-27 06:55

    You are falling foul of a restriction upon the intermixing of read and write operations on a file opened in update mode that MS's fstream library inherits from from the its C <stdio.h> implementation.

    The C Standard (I cite C99, but it doesn't differ in this point from C89) at 7.19.5.3/6 states:

    When a file is opened with update mode ('+' as the second or third character in the above list of mode argument values), both input and output may be performed on the associated stream. However, output shall not be directly followed by input without an intervening call to the fflush function or to a file positioning function (fseek, fsetpos, or rewind), and input shall not be directly followed by output without an intervening call to a file positioning function, unless the input operation encounters end- of-file.

    (my emphasis).

    So your stream.seekp(1) solution, which devolves to a C fseek, is correct.

    The GNU C library does not have this Standard limitation, so your code as posted works as expected when built with GCC.

    The MS <fstream> library is compliant with the C++ Standard in inheriting this restriction. fstreams are implemented using basic_filebuf<charT,traits>. In the (C++11) Standard's account of this template, at § 27.9.1.1/2, it simply says:

    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.

    0 讨论(0)
  • 2020-11-27 06:56

    You may want to look into tied streams - http://www.cplusplus.com/reference/ios/ios/tie/

    This makes every time an input reads the output will automatically be flushed, which is I think the behavior you want, although it does require a separate input and output stream

    0 讨论(0)
提交回复
热议问题