How to read and write binary files

Hi, C++ newbie here. I need to read and write certain bytes in binary files. After searching here and on google, I tried this to read:

1
2
3
4
5
6
7
8
string path = "/home/..."; // path
fstream file (path.c_str(), ios::in | ios::binary | ios::ate);
int size = file.tellg();
file.seekg(ios::beg);
string content;
content.resize(size);
file.read(&content[0], content.size());
file.close();

But this lead me to problems for bytes >= 128.

So I realized I could use vector<unsigned char> instead of string:
1
2
3
vector<unsigned char> content;
content.resize(size);
file.read((char *) &content[0], content.size());

Is this approach ok? No side effects?

And last, I still haven't figured out how to write back to the file.
Suppose I have this:
1
2
3
4
5
vector<unsigned char> content;
content.resize(3);
content[0] = 0x01;
content[1] = 0xFF;
content[2] = 0xFF;

Would do write them to position 0x118B1, for example?


Thanks
Infante wrote:
Is this approach ok? No side effects?

Yes.

Infante wrote:
Would do write them to position 0x118B1, for example?


1
2
file.seekp(0x118b1);
file.write((char*)&content[0],content.size());


Don't forget to open it with the flag ios::out.
Last edited on
Do you mean seekp?

From what I've tested, if I do that, the rest of the file is gone. Do I need to read it entirely to a string/vector, change just the bytes I need in the string/vector, then write all the file again?
Infante wrote:
Do you mean seekp?

Ah yes, of course.

Infante wrote:
From what I've tested, if I do that, the rest of the file is gone. Do I need to read it entirely to a string/vector, change just the bytes I need in the string/vector, then write all the file again?

No, that's not necessary. The rest of the file should remain completely unaffected.
1
2
3
4
5
6
7
8
9
10
11
    fstream arq("/tmp/myfile", ios::binary | ios::out);
    int pos = 0x11882;
    vector<int> melda;
    melda.resize(3);
    melda[0] = 0x00;
    melda[1] = 0x08;
    melda[2] = 0xFF;
    arq.seekp(pos);

    arq.write((char *) &melda[0], melda.size());
    arq.close();


This erases the rest of the file.
You also need to specify ios::in. If you're opening it in write-only mode, it will truncate the file to 0 bytes when it is opened.
Also, if you want to write all three ints, you need to write melda.size()*sizeof(int) characters.
Hi,

You were right about ios::in (forgot that).
But something went wrong. File was:
00 09 ff ff ff ff 00 00 00 00 00

and became:

00 00 00 00 08 00 00 00 ff 00 00

I see the 00 08 and ff there, but certainly more than the 3 bytes were written.


It only wrote correctly using a vector<unsigned char> and specifying 3 as size.
Topic archived. No new replies allowed.