binary and out mode to open a file

binary and out mode to open a file

When I use binary and out mode to open a exist file, and to modify the 4th and 8th byte data to 0x78, I found that the whole file will be rewrite, like below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <fstream>
#include <iostream>
using namespace std;

int main(int argc, char **argv)
{
fstream out;
out.open("./test.txt", ios_base::binary | ios_base::out);

uint8_t data = 0x78;

out.seekp(4, ios_base::beg);
out.write((char *)&data, 1);

out.seekp(8, ios_base::beg);
out.write((char *)&data, 1);

out.close();
return 0;
}

And the file original data is :

1
FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF

But the file modified is:

1
00 00 00 00 78 00 00 00 78

I have tried ios::app and ios::ate, the ios::app will out put my data at the end of the file and the skeep do not work.

Finally, I thought out that the file is just a out file, so the api will not see the original data of the file, so I should add the ios::in.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <fstream>
#include <iostream>
using namespace std;

int main(int argc, char **argv)
{
fstream out;
out.open("./test.txt", ios_base::binary | ios_base::out | ios_base::in);

uint8_t data = 0x78;

out.seekp(4, ios_base::beg);
out.write((char *)&data, 1);

out.seekp(8, ios_base::beg);
out.write((char *)&data, 1);

out.close();
return 0;
}

And finally, I got the right data.

1
FF FF FF FF 78 FF FF FF 78 FF FF FF FF FF FF FF