Arpit
Arpit

Reputation: 105

C++: Patching a binary file using fstream

I have a huge file that is already created. I need to write some data at the start of the file while retaining the other contents of the file as such. The following code corrupts the existing file. Can anyone help me with the right method.

 ofstream oFile(FileName,ios::out|ios::binary);  
 oFile.seekp(0);  
 oFile.write((char*)&i,sizeof(i));       
 oFile.write((char*)&j,sizeof(i));
 oFile.close();

EDIT: Basically I want to overwrite some bytes of an already existing file at different locations including start. I know the byte address of locations to write. My write will not change the file size.

I need to do something equivalent to the following code that works:

int  mode = O_RDWR;
int myFilDes = open (FileName, mode, S_IRUSR | S_IWUSR);
lseek (myFilDes, 0, SEEK_SET);
write (myFilDes, &i, sizeof (i));
write (myFilDes, &j, sizeof (j));

Upvotes: 3

Views: 1317

Answers (3)

smatter
smatter

Reputation: 29168

You are missing ios::in

Use:

ofstream oFile(FileName,ios::out|ios::in|ios::binary);

Upvotes: 1

fpointbin
fpointbin

Reputation: 1663

If you wanna "insert", you've have to know that C++ see the "file" like a stream of bytes... So if you have got it:

|1|5|10|11|2|3|

And you wanna insert data in the first position( set your position at 0 ), you will have to move the rest of the file...

Upvotes: 0

Anya Shenanigans
Anya Shenanigans

Reputation: 94584

you should perform an:

 oFile.seekp(0);

before performing the write. ios::ate implies you're appending to the file.

You also need to use ios::in instead of ios::out. ios::out implies you plan on truncating the file, which may have unintented consequences.

It's not intuitive

Upvotes: 3

Related Questions