2017-06-01 76 views
2

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

_size + 1 * sizeof(char)_ == size + sizeof(char)...我想这不是你的意思 – CIsForCookies

+0

当然'strstr'不会工作,因为它在NUL终止操作字符串。你需要编写你自己的“binbin”函数,例如,这个签名:'char * binbin(const char *,const char * haystack,int length)'。虽然我没有检查其他问题。 –

+0

由于fread会将数据复制到一个char数组中,该数组的末尾有0,这不就像NUL终止字符串一样吗? – CIsForCookies

回答

0

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

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