简体   繁体   中英

C++ replace data in binary file with fstream

I try to replace data in binary file using C++ and fstream library. Is it possible to do that with this library? I would like to change one byte of file in address: 0xB07 to 1.

I have written the following code snippet:

...

int address = 0xB07;
char * toChange = new char('0');

std::ifstream input(filename, std::ios::binary);
input.seekg(address);
input.read(toChange, 1);
input.close();

*toChange = (char)0x01;

std::ofstream output(filename, std::ios::binary);
output.seekp(address);
output.write(toChange, 1);
output.close();

...

I have tried many versions of this code and I still can't understand why the byte doesn't change.

This code will remove your file and put totally new contents in it. The problem is in line

std::ofstream output(filename, std::ios::binary);

That's because the default open mode is ios::out | ios::trunc ios::out | ios::trunc (See for ex.: Input/Output with files ) Which means file is being truncated to zero bytes.

Then your seek() function extends him to the specified size (usually filling with zeroes) and finally output.write() writes the byte at the end.

In order to do what you want I had to specify the following ofstream flags: std::ios::binary|std::ios::out|std::ios::in

I cannot say currently for sure why the std::ios::in is needed, sorry...

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