Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 725
Jonny Schubert Avatar asked Jun 21 '11 15:06

Jonny Schubert


4 Answers

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);
  }
}
like image 180
Nim Avatar answered Nov 16 '22 12:11

Nim


When opening with ios::app, it is as if you open a new file that just happened to be attached to an existing file: you can not access the existing file. I'm not sure, because I would do as in Kerrek's answer, but if you really want to try, you probably have to open with "ios::in | ios::out", similar to fopen("test.txt", "rw").

Or as crashmstr points out: ios::out might be enough.

like image 6
stefaanv Avatar answered Nov 16 '22 12:11

stefaanv


You cannot magically extend the file from the middle. Perhaps easiest to write to a new file: First copy the initial segment, then write your new data, then copy the remaining segment. When all is done, you can overwrite the original file.

like image 5
Kerrek SB Avatar answered Nov 16 '22 14:11

Kerrek SB


According to the specification of fstream here

fstream::open

the ios::app "Sets the stream's position indicator to the end of the stream before EACH output operation." So ios::app doesn't work for replacing, seeks of any sort fail, at least for me.

Just using ios::out does wipe out the file contents preserving only the size, basically turning the file into trash.

ios::in|ios::out turned out as the only working thing for me.

like image 3
Aleksey Avatar answered Nov 16 '22 13:11

Aleksey