我正在嘗試掃描二進制檔案中的病毒簽名(不使用 strstr()),并列印是否找到簽名。但是代碼不起作用。我在函式之外讀取了檔案。
不幸的是,即使我試圖掃描病毒簽名本身,該代碼也不起作用。
int searchForSignature(FILE* file_to_search, FILE* virus) {
int v_size = 0;
int f_size = 0;
fseek(virus, 0L, SEEK_END);
v_size = ftell(virus);
fseek(virus, 0, SEEK_SET);
fseek(file_to_search, 0L, SEEK_END);
f_size = ftell(file_to_search);
fseek(file_to_search, 0, SEEK_SET);
printf("VIRUS SIZE: %d FILE SIZE: %d\n", v_size, f_size);
if (v_size > f_size)
{
printf("VIRUS NOT FOUND\n");
return 1;
}
int counter = 0; char ch = ' '; char ch2 = ' ';
while ((ch = (char)fgetc(file_to_search)) != EOF)
{
printf("%d\n", counter);
if (counter == v_size)
{
printf("VIRUS FOUND\n");
return 0;
}
else
{
ch2 = (char)fgetc(virus);
if (ch == ch2)
{
counter ;
}
else
{
counter = 0;
}
}
}
printf("VIRUS NOT FOUND\n");
return 1;
}
我如何讀取函式之外的檔案:
FILE* virus_file = NULL;
virus_file = fopen("example file path", "rb");
if (virus_file == NULL)
{
printf("Error opening file");
return 1;
}
FILE* file_to_scan = NULL;
file_to_scan = fopen("example file path 2", "rb");
if (file_to_scan == NULL)
{
printf("Error opening file");
return 1;
}
uj5u.com熱心網友回復:
至少這些問題
成功為時已晚
counter == v_size之后可能是真的counter ;。檔案中可能不存在下一個回圈的if (counter == v_size). 而是counter == v_size在遞增后立即進行測驗。
沒有重置
如果只找到部分匹配,則匹配測驗不應在下一個源檔案字符上恢復,而是回到比較的開頭,然后前進 1。
考慮:
search file: "aaac"
virus: "aac"
在“aa(a)...”(第三個“a”)上搜索搜索檔案失敗,但需要在“a(a)”(第二個“a”)上繼續。
病毒檔案需要rewind()匹配失敗。我建議將整個病毒簽名讀取到分配的記憶體中(例如:unsigned char *virus = malloc(v_size);而不是從檔案中重新讀取。
資訊丟失
int fgetc()回傳 257 個不同的值:0-255 和EOF. 保存該結果char會丟失資訊。使用int ch = fgetc(...), int ch2 = fgetc(...)。
這可以解釋 OP 的“代碼不起作用,即使我試圖掃描病毒簽名本身。” 因為其中一個病毒位元組EOF在轉換為char.
不需要演員來解決這個問題。
型別長度錯誤
ftell(virus)回傳一個long。將結果保存在 anint中可能會丟失資訊。這里的代碼也缺少錯誤檢查。
不需要的代碼
if (v_size > f_size)不需要塊。
選擇
// Pseudo code
Read virus into an allocated buffer.
Read a chunk of test file into a test buffer at least 2x virus size.
Walk test buffer (1 char at a time) trying `memcmp()`.
Stop if match found,
until remaining test buffer not full enough for a possible match.
Move remaining test buffer to start and re-fill as able.
If not able to re-fill at all, we are done - no match.
這是 O(test_size * virus_size)。更復雜的“walk”是 O(test_size virus_size)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/473133.html
上一篇:C編程中的整數提升
