C ++: fixing binary using fstream

I have a huge file that has already been created. I need to write some data at the beginning of the file, while preserving the other contents of the file. The following code distorts an existing file. Can someone help me with the correct 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 rewrite a few bytes of an existing file in different places, including start. I know the byte address of the locations to write. My record will not resize the file.

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));
+3
source share
3 answers

You are lacking ios::in

Using:

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

+1
source

you must do:

 oFile.seekp(0);

before recording. ios :: ate implies what you are adding to the file.

ios:: in ios:: out. ios:: out , , .

+3

If you want to "paste", you need to know that C ++ sees the "file" as a stream of bytes ... So, if you have this:

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

And you want to paste the data in the first position (set your position to 0), you have to move the rest of the file ...

0
source

Source: https://habr.com/ru/post/1796705/


All Articles