简体   繁体   中英

Binary output to file in random positions in C++

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

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM