1

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?

2
  • Do you remember to close the file after having written to it? Commented Aug 17, 2011 at 21:58
  • It seems to me that this should not affect the result. However, the code is run separately - that is, recorded first, then updated, then started to read. Commented Aug 17, 2011 at 22:02

1 Answer 1

3

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:in AND ios:out despite the fact you're writing only. So essentially I'd use the following:

ofstream ofs("file", ios::binary | ios::in | ios::out | ios::ate);

This should open the file with the stream/file pointer being at the end of the file (ios::ate might be optional though).

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.