繁体   English   中英

如何检查字符串是否在二进制文件中

[英]How to check if a string is in a binary file

我正在制作一个程序,该程序获取两个二进制文件,并检查第二个文件(字符串)是否在第一个文件中。 我尝试使用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");
    }

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM