Editing a big file in C++

I would like to know if there is a simple way to edit a binary file without rewriting it all or loading it in memory.

For example if I want to modify from byte 10 to byte 20 of a 4TB file.

Thank you for your help.
Open the file for i/o in binary mode, seek to the starting byte, then write the required data to overwrite what is already there.

See
http://www.cplusplus.com/reference/ostream/ostream/seekp/
http://www.cplusplus.com/reference/ostream/ostream/write/
Last edited on
If you're not changing the length of the file at all, then you can just edit the bytes you want in situ.

Otherwise, you have to rewrite the whole file.
Thank you for replies. Why in my code it overwrites the file, which becomes of 3 bytes of length?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
void change_byte()
{
    std::ofstream f{ _fname, std::ios_base::binary };

    if (f)
    {
        f.seekp(2);
            
        char* buffer = new char[1];
        buffer[0] = 0x88;

        f.write(buffer, 1);

        delete[] buffer;

        f.close();
    }
    else
    {
        throw std::runtime_error("File error.");
    }
}
Last edited on
I found the solution, opening file with:

 
std::ofstream f{ _fname, std::ios_base::binary | std::ios_base::out | std::ios_base::in };

Thank you for your help.
Last edited on
Topic archived. No new replies allowed.