C中的二进制补丁(而不是xxd)



我一直在写shell脚本(为了更容易使用(,但这次我想用C来写,我用得最多的一个命令是xxd -r,用来"修补"二进制文件。

示例:

echo "0000050: 2034" | xxd -r - my_binary_file

我的问题是:有没有一种方法可以在C中做类似的事情?

(我希望我的问题很清楚(

在通用情况下,您可以使用fopen(在Unix上使用"w",在Windows上使用"wb"(、fseek和fwrite。

如果你喜欢posix风格,打开、寻找和写作。

在Win32上,posix等价物是CreateFile、SetFilePointer和WriteFile

您仍然可以使用您的命令,并使用system((函数在C代码中调用它。

系统("echo"0000050:2034"|xxd-r-my_binary_file"(

注意:您可以使用sprintf((函数动态构建带有文件名和参数的上述字符串,然后将其传递给系统函数((,如下所示。

#include <string.h>
#include <stdlib.h>
int main(){
char acBuffer[512]; //Allocate as reuiquired only
memset(acBuffer, 0x00, sizeof(acBuffer));
sprintf(acBuffer, "echo "%s" | xxd -r - %s", "0000050: 2034", "YourBinaryFile");
system(acBuffer); //You can check the return type if you want to
return 0;
}

最新更新