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.