Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overwrite byte in file without clearing it

Tags:

c++

file

byte

How to overwrite a byte in a file without clearing the entire file? Note that I don't want to insert additional bytes but rather overwrite a byte at a certain offset.

I have tried the following code to write a byte at some offset. However this clears everything after the specified offset which is not what I want.

#include <fstream>

int main()
{
    std::ofstream ofs {"foo", std::ios::binary};
    ofs.seekp(0x2);
    ofs.put(0x7);
}

In general people on SO seem to suggest reading the entire file then changing it in memory and then writing it out again. However that seems too much work to just change a single byte.

Is it not possible to overwrite a single byte in-place?

like image 219
user14015333 Avatar asked Oct 25 '25 04:10

user14015333


1 Answers

It's perfectly possible (in fact common) to update a file, provided you don't want to insert any new bytes before the current end of file.

Change to this

std::ofstream ofs {"foo", std::ios::in|std::ios::out|std::ios::binary};

However this will fail if the file does not exist, but it sounds like that is not a concern.

By just using std::ios::binary (which the ofstream constructor adjusts to std::ios::out|std::ios::binary) you destroyed the file contents. Your code then took advantage of a little known feature of C/C++ I/O which is that it is possible to seek beyond the end of a file. If any bytes are written when the file is in this state the gap between the file end and the current position is filled with zeros.

Here's a reference on what the different file modes do.

like image 123
john Avatar answered Oct 26 '25 18:10

john



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!