Write to the middle of an existing binary file c++

Jonny Schubert picture Jonny Schubert · Jun 21, 2011 · Viewed 15.7k times · Source

I'm trying to open a binary file for writing without erasing the content. But I do not want to write to eof. I want to write to a specific position in file.

Here is a litte example:

ofstream out("test.txt", ios::binary | ios::app);
for(int i = 0; i < 100; i++)
    out.put('_');
out.write("Hallo", 5);
out.close();

ofstream out2("test.txt", ios::binary | ios::app);
out2.seekp(10);
out2.write("Welt", 4);
out2.close();

If using app, seek doesn't work. If not using app opening file erases data. Does anybody know an answer?

Answer

Nim picture Nim · Jun 21, 2011

try the second overload of seekp, which allows you to provide an offset and a direction, this could be begining of file in your case (i.e. ios_base::beg). This of course assumes you know what you are doing and all you want to do is overwrite an existing number of characters.

EDIT: here is fully working example:

#include <iostream>
#include <fstream>

using namespace std;
int main()
{
  {
    ofstream out("test.txt", ios::binary);
    for(int i = 0; i < 100; i++)
      out.put('_');
    out.write("Hallo", 5);
  }

  {   
    fstream out2("test.txt", ios::binary | ios::out | ios::in);
    out2.seekp(10, ios::beg);
    out2.write("Welt", 4);
  }
}