2017-06-01 129 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字節在你的字符串
相關問題