2017-06-06 99 views
-4

我不知道爲什麼這段代碼無法正常工作。在二進制文件中查找模式/在二進制文件中查找匹配(C)

while (TRUE) 
{ 
    do 
    { 
     fread(buffer1, BUFFER_LEN - 1, 1, pFile); 
     fread(buffer2, BUFFER_LEN - 1, 1, pVirus); 
     if (feof(pVirus)) 
     { 
      printf("MATCH!\n"); 
      flag = 1; 
      break; 
     } 
    } while (strcmp(buffer1, buffer2) == 0); 

    if (buffer1 != buffer2) 
    { 
     rewind(pVirus); 
    } 

    if (feof(pFile) || flag == 1) 
    { 
     break; 
    } 
} 

fclose(pFile); 
fclose(pVirus); 

在較大的文件中的小文件代碼找到匹配代碼不起作用。

+1

比較內存使用'strcmp'將失敗,如果它有零。 –

+0

我應該如何比較? – Justeton

+2

Google或man memcmp – ThingyWotsit

回答

0

以下提議代碼:

  1. 執行所需功能
  2. 不能說這完全編譯爲有機磷農藥張貼代碼是不完整的
  3. 不會賽格故障

現在建議代碼:

rewind(pFile); 
    do 
    { 
     size_t buf1Count = fread(buffer1, 1, BUFFER_LEN, pFile); 
     if(!buf1Count) 
     { 
      if(feof(pFile)) 
      { // reached end of pFile 
       ??? 
       break; 
      } 

      else 
      { // error event 
       perror("fread of pFile failed"); 
       fclose(pFile); 
       fclose(pVirus); 
       exit(EXIT_FAILURE); 
      } 
     } 

     rewind(pVirus); 
     do 
     { 
      size_t buf2Count = fread(buffer2, 1, BUFFER_LEN, pVirus); 

      if(!buf2Count) 
      { 
       if(feof(pVirus)) 
       { // reached end of pVirus 
        printf("NO MATCH\n"); 
        break; 
       } 

       else 
       { // error event 
        perror("fread of pVirus failed"); 
        fclose(pFile); 
        fclose(pVirus); 
        exit(EXIT_FAILURE); 
       } 
      } 

      if(memcmp(buffer1, buffer2, buf1Count) == 0) 
      { 
       printf("MATCH\n"); 
       break; 
      } 
     } while(1); 
    } while (1); 

    fclose(pFile); 
    fclose(pVirus);