3

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));
5
  • 2
    Are you intending to append new bytes to the front of the file or overwrite it? Commented Mar 7, 2011 at 0:37
  • You will need to test in an hexadecimal editor, then when it works, pass it to C++. Commented Mar 7, 2011 at 0:39
  • @GWW: You don't "append new bytes to the front". That would be prepending. Commented Mar 7, 2011 at 0:49
  • @Tomalak: Thanks, I can't edit my my comment. My brain is broken apparently :P. Commented Mar 7, 2011 at 0:52
  • Basically I want to overwrite some bytes of an already existing file at different locations including start. I know the offset to write. My write will not change the file size. Commented Mar 7, 2011 at 0:52

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

I tried it. But the original file gets overwritten. Could you pls check the edited question.
@Arpit: The answer you later accepted says the same thing as this answer in less detail.
1

You are missing ios::in

Use:

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

Comments

0

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...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.