【问题标题】:How can I carve out one binary file from a concatenated binary如何从连接的二进制文件中分割出一个二进制文件
【发布时间】:2020-05-26 17:38:39
【问题描述】:

基本上,我在 Linux 上使用“cat”命令组合两个二进制文件。 我希望能够使用 C 再次将它们分开 这是我目前得到的代码

int main(int argc, char *argv[]) {

    // Getting this file 
    FILE *localFile = fopen(argv[0], "rb");

    // Naming a new file to save our carved binary
    FILE *newFile = fopen(argv[1], "wb+");

    // Moving the cursor to the offset: 19672 which is the size of this file
    fseek(localFile, 19672, SEEK_SET);

    // Copying to the new file
    char ch;
    while ( ( ch = fgetc(localFile) ) != EOF ) {
        fputc(ch, newFile);
    }
}

【问题讨论】:

  • 你的问题是什么?
  • fgetc 返回 int,而不是 char
  • 您希望它适用于本示例还是一般情况下?因为如果你不知道大小并且没有任何分隔符分隔两个文件是不可能的。
  • cat命令在哪里使用?这似乎是 C 源代码,没有来自它的系统调用。
  • 我确实知道原始文件(file1)的大小,所以我想将光标移动到该偏移量,因为另一个文件应该位于那里

标签: c binary concatenation fopen fseek


【解决方案1】:

假设您已经知道第二个文件的开始位置。您可以进行如下操作。 (这是最低限度的)

#include <stdio.h>
#include <unistd.h>

int main()
{
    FILE* f1 = fopen("f1.bin", "r");
    FILE* f2 = fopen("f2.bin", "w");

    long file1_size = 1;

    lseek(fileno(f1), file1_size, SEEK_SET);

    char fbuf[100];
    int rd_status;

    for( ; ; ) {
        rd_status = read(fileno(f1), fbuf, sizeof(fbuf));

        if (rd_status <= 0)
            break;
        write(fileno(f2), fbuf, rd_status);
    }

    fclose(f1);
    fclose(f2);
    return 0;
}

输入文件--f1.bin

1F 2A 

输出文件--f2.bin

2A

请根据您的示例修改文件名和文件大小。

【讨论】:

  • 您好,感谢您的回答。原来我在做char ch 我应该做int ch 如何将问题标记为已解决? :D
  • 是的,根据fgetc() 手册页,它返回unsigned char 类型转换为int。但在不太严重的情况下,您需要避免逐字节读取。因为您执行磁盘 IO 的次数更多。您应该考虑使用read 的变体来获得高效的代码。请访问此链接,accepting-answeres
猜你喜欢
  • 1970-01-01
  • 2010-10-10
  • 2014-08-13
  • 1970-01-01
  • 2010-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多