1

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.

5
  • As you have not provided a Minimal, Complete, and Verifiable example that we could try for ourselves, we are limited to your description. So what does "it doesn't work" mean? Do you get some error message? Something unexpected happens? (what is it?) Commented Nov 21, 2018 at 14:33
  • Sorry for that. 'It doesn't work' means that the bytes aren't replaced. I can check them for example in Hex Editor. Commented Nov 21, 2018 at 14:40
  • Try adding error checking to the write part. Maybe the file is not actually writable? At least it would tell you which part is failing. Commented Nov 21, 2018 at 14:45
  • I hope my question is better now. How to add error checking? I have tried to check output.bad() but it returns false. Commented Nov 21, 2018 at 15:00
  • Can an ofstream constructor fail? How does it indicate failure? Check for it. Can seekp fail? How does it... (etc.) To answer the Hows, look at the reference cplusplus.com/reference/fstream/ofstream Commented Nov 21, 2018 at 15:03

1 Answer 1

1

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 (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::inis needed, sorry...

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.