【问题标题】:How to check if a string is in a binary file如何检查字符串是否在二进制文件中
【发布时间】:2017-06-01 11:29:47
【问题描述】:

我正在制作一个获取两个二进制文件的程序,并检查第二个文件(字符串)是否在第一个文件中。 我尝试使用 strstr 函数,但它不起作用。这是我的代码的一部分: 我读的文件对吗?

    fseek(fileToCheckv, 0 , SEEK_END);
    size = ftell(fileToCheckv);
    rewind(fileToCheckv);
    fseek(virusSignit, 0L, SEEK_END);
    vsize = ftell(virusSignit);
    rewind(virusSignit);
    buffer = (char*)realloc(buffer, size+1 * sizeof(char));
    virusSig = (char*)realloc(virusSig, vsize+1 * sizeof(char));
    buffer[size] = 0;
    virusSig[vsize] = 0;
    fread(buffer,1 , size, fileToCheckv);
    fread(virusSig,1 ,vsize, virusSignit);
    result = strstr(buffer, virusSig);
    if (result != NULL)
    {
        printf("\nVirus was found in file: %s\n", fileToOpen);
    }
    else
    {
        printf("The virus was not found\n");
    }

【问题讨论】:

  • size+1 * sizeof(char) == size + sizeof(char)... 我猜这不是你的意思
  • 当然strstr 不会工作,因为它在 NUL 终止的字符串上运行。您需要编写自己的“binbin”函数,例如这个签名:char *binbin(const char *needle, const char *haystack, int length)。不过我没有检查其他问题。
  • 既然 fread 会将数据复制到一个结尾为 0 的 char 数组中,这不就和 NUL 终止的字符串一样吗?
  • @CIsForCookies 是的。
  • @joop memmem 是一个 gnu 扩展。它在 Windows 上不存在,但重写并不难。

标签: c binaryfiles fread strstr fgetc


【解决方案1】:

您可以正确打开文件,但还有其他一些小问题:

  • buffer = (char*)realloc(buffer, size+1 * sizeof(char));。您可能打算简单地执行 size+1(size+1) * sizeof(char),因为 sizeof(char) 将始终为 1。此问题在您的代码中出现两次
  • 在同一行中,您使用realloc 而不检查指针是否为NULL。如果分配失败,这可能会出现问题
  • 正如@Michael Walz 所说,strstr() 用于以 NUL 结尾的字符串,因此对于二进制文件,您应该为二进制文件创建自己的类似strstr 的函数,或者验证字符串中没有 NUL 字节

【讨论】:

    猜你喜欢
    • 2020-02-28
    • 1970-01-01
    • 2022-10-13
    • 2014-08-10
    • 2011-01-13
    • 2011-11-29
    • 2020-10-16
    • 1970-01-01
    • 2011-03-06
    相关资源
    最近更新 更多