简体   繁体   English

C ++:使用fstream修补二进制文件

[英]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. 编辑:基本上我想覆盖包括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. ios :: ate意味着你要附加到文件中。

You also need to use ios::in instead of ios::out. 您还需要使用ios :: in而不是ios :: out。 ios::out implies you plan on truncating the file, which may have unintented consequences. ios :: out意味着你计划截断文件,这可能会产生无意义的后果。

It's not intuitive 这不直观

You are missing ios::in 你缺少ios::in

Use: 使用:

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

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: 如果你想“插入”,你必须知道C ++看到的“文件”就像一个字节流...所以如果你有它:

|1|5|10|11|2|3| | 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... 而你想在第一个位置插入数据(将你的位置设置为0),你将不得不移动文件的其余部分......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM