C++ – fstream replace portion of a file

cfstreamio

When I do

fstream someFile("something.dat", ios::binary|ios::out);
someFile.seekp(someLocation, ios::beg);
someFile.write(someData, 100);

It seems to replace the entire file with those 100 bytes instead of replacing only the appropriate 100 bytes, as if I had specified ios::trunc. Is there a portable way to not have it truncate the file?

Edit: adding ios::in seems to do the trick, by why is this required, and is that standard behavior?

Edit #2: I am not trying to append to the existing file. I need to replace the 100 bytes while leaving the rest unaffected.

Best Answer

You want the append flag, ios::app, if you want to write at the end of the file.

To do it somewhere arbitrarily in the middle of the file, you need to seek to the right place. You CAN do this by opening the file for in and out, but if I were you I'd create a temp file, copy input up to mark, write your new data, copy the rest to EOF, close the files and replace the previous version with the temp file. This is called a "Master File update".