Reading and writing to the same file using the same fstream

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 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-

(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 §, 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.

Leave a Comment