I encountered a problem and my current knowledge of C++ is not enough to solve it. I looked for the answer in books of Stroustrup, but a full understanding of what I’m doing wrong for me not now.
So the essence.
I write to the file:
int i = 1;
int j = 2;
ofstream ofs("file", ios::binary);
ofs.write(as_bytes(i), sizeof(int));
ofs.write(as_bytes(j), sizeof(int));
After that, I need to update the second value:
int j = 10;
ofstream ofs("file", ios::binary);
ofs.seekp(4, ios::beg);
ofs.write(as_bytes(j), sizeof(int));
And when I try to read the file:
int i = 0;
int j = 0;
ifstream ifs("file", ios::binary);
ifs.read(as_bytes(i), sizeof(int));
ifs.read(as_bytes(j), sizeof(int));
cout << i << ' ' << j << endl;
It turns out that I lose the first value. What am I doing wrong? Why did it disappear?
By default the file will be truncated (
ios:trunc, i.e. the content is lost upon opening the file for writing).For the second write operation explicitly add the flags
ios:inANDios:outdespite the fact you’re writing only. So essentially I’d use the following:This should open the file with the stream/file pointer being at the end of the file (
ios::atemight be optional though).