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. So I try to use the following code:
std::fstream stream("filename", std::ios::in | std::ios::out | std::ios::binary);
char byte;
stream.read(&byte, 1);
// stream.seekp(1);
int bytesCount = 4096;
auto bytesVec = std::vector<char>(bytesCount, 'c');
char* bytes = bytesVec.data();
std::cout << stream.bad() << std::endl;
stream.write(bytes, bytesCount);
std::cout << stream.bad() << std::endl;
If I execute this code, the first bad()
returns false
, but the second one returns true
and nothing actually gets written.
If I decrease bytesCount
to anything smaller than 4096 (presumably the size of some internal buffer), the second bad()
returns false
, but still nothing gets written.
If I uncomment the seekp()
line, the writing starts working: bad()
returns false
and the bytes actually get written.
Why is the seekp()
necessary here? Why doesn't it work without it? Is the seekp()
the right way to do this?
I'm using Visual Studio 2012 on Windows 7.
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. fstream
s 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.