Question

I'm beginning to feel awkwardly stupid, but I have a problem with outputting binary data to a file. I have a file, let's say, 1000 bytes long. What I would like to do, in C++, is simply opening the file, replace ONE byte in a given position (let's say, the i-th byte), and close it.

File before operation: AAAAAA File after operation: AAABAA

What is the easiest way to do so? I tried to open it with a ofstream.open, with the following modes:

ios::binary|ios::out
ios::binary|ios::app
ios::binary|ios::ate

All of these affected the actual size of the file after the operation. What should I do? I'm beginning to feel desperate.

Thank you very much and merry christmas to everybody!

Matteo

Was it helpful?

Solution

Besides binary mode, you need to open it in out and in modes. This corresponds to the fopen mode "r+b" which opens a file for reading and writing, and doesn't truncate the file if it exist (in fact, it must exist or you will fail to open the file).

References:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top