【问题标题】:binary patch in C (instead of xxd)C 中的二进制补丁(而不是 xxd)
【发布时间】:2020-07-25 19:19:11
【问题描述】:

我一直在编写 shell 脚本(为了让事情更容易使用),但这次我想用 C 语言来做,我最常用的一个命令是xxd -r,用于“修补”二进制文件。

示例:

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

我的问题是:有没有办法在 C 中做类似的事情?

(希望我的问题很清楚)

【问题讨论】:

    标签: c binary hex


    【解决方案1】:

    通常,您可以使用fopen(在 Unix 上使用“w”,在 Windows 上使用“wb”)、fseekfwrite

    如果您更喜欢 posix 样式,openseekwrite

    在 Win32 上,posix 等效项是 CreateFileSetFilePointerWriteFile

    【讨论】:

    • 如果你使用fopen(),你必须使用"rb+"以避免截断文件。
    • 点赞FILE *fd = fopen(my_binary_file, "rb+");fseek(fd, 0, 0x10);fwrite(??, ??, 1, fd);
    • fseek(fd, 0x50, SEEK_SET)
    • 我不想剥夺你学习的机会。但是你明白了一般的想法。打开文件,将文件句柄传递给 fseek,在该地址写入一个或多个字节。不要忘记调用 fclose。 (posix:关闭,win32:CloseHandle)。并且始终检查返回值是否有错误。
    【解决方案2】:

    您仍然可以使用您的命令并使用 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)
    猜你喜欢
    • 2010-09-05
    • 2020-07-21
    • 2010-12-29
    • 1970-01-01
    • 2020-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多