How to edit a binary file in C++?

Joined
Mar 3, 2011
Messages
2
Reaction score
0
Hi, I'm new to C++.
I'm trying to edit a binary file. This is for an old video game.

To test, I created a file that has only 4 bytes and I'm trying to read and write the first 3 bytes. Reading is fine, but I'm not able to write.

This is how I'm reading it:
Code:
fstream file ("/home/me/file", ios::in | ios::binary);
int size = 3;
vector<unsigned char> content;
content.resize(size);

file.read((char *) &content[0], size);
file.close();

It works fine.

The problem is when I try to write:
Code:
fstream file ("/home/me/file", ios::in | ios::binary | ios::out);
int size = 3;
vector<unsigned char> content;
content.resize(size);
content[0] = (unsigned char) 0xAA;
content[1] = (unsigned char) 0xAA;
content[2] = (unsigned char) 0xAA;

file.write(reinterpret_cast <const char*> (&fileContent), size);
file.close();

This doesn't work. The values written are not 0xAA. In fact, it writes 3 different bytes.
And what's worse: if I run it again, it will write more 3 different bytes. Looks random.

Can anyone give me a hand on this?

Thanks.
 
Joined
Mar 3, 2011
Messages
2
Reaction score
0
Code:
file.write(reinterpret_cast <const char*> (&fileContent), size);
Should be:
Code:
file.write(reinterpret_cast <const char*> (&fileContent[0]), size);

I guess I was writing the memory address instead of the array content, that's why I got different values every run.

A bit upset I took many days to figure that, but at least it was something simple. C/C++ can freak you out when you're used to higher level languages :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,810
Latest member
Kassie0918

Latest Threads

Top