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));
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With