【发布时间】:2020-07-25 19:19:11
【问题描述】:
我一直在编写 shell 脚本(为了让事情更容易使用),但这次我想用 C 语言来做,我最常用的一个命令是xxd -r,用于“修补”二进制文件。
示例:
echo "0000050: 2034" | xxd -r - my_binary_file
我的问题是:有没有办法在 C 中做类似的事情?
(希望我的问题很清楚)
【问题讨论】:
我一直在编写 shell 脚本(为了让事情更容易使用),但这次我想用 C 语言来做,我最常用的一个命令是xxd -r,用于“修补”二进制文件。
示例:
echo "0000050: 2034" | xxd -r - my_binary_file
我的问题是:有没有办法在 C 中做类似的事情?
(希望我的问题很清楚)
【问题讨论】:
通常,您可以使用fopen(在 Unix 上使用“w”,在 Windows 上使用“wb”)、fseek 和 fwrite。
如果您更喜欢 posix 样式,open、seek 和 write。
在 Win32 上,posix 等效项是 CreateFile、SetFilePointer 和 WriteFile
【讨论】:
fopen(),你必须使用"rb+"以避免截断文件。
FILE *fd = fopen(my_binary_file, "rb+"); → fseek(fd, 0, 0x10); → fwrite(??, ??, 1, fd);
fseek(fd, 0x50, SEEK_SET)
您仍然可以使用您的命令并使用 system() 函数在 C 代码中调用它。
system("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;
}
【讨论】:
system() 那就太好了(否则它不是真正的 C)