我尝试创建一个比较2个文件的程序,并检查第一个文件中是否存在第二个文件。 函数r_scan进入无限循环。 有人知道为什么它不起作用?
这是我的代码:
/**
The function scan the file and check if there is a virus in the file.
Input:
virus_address - The address of the virus file.
scaned_address - The adress of the file that we scan.
Output:
end - If the the file infected. 0 - infected, 1 - not infected.
**/
int r_scan(char* virus_address, char* scaned_address)
{
//INIT
char v = ' ', s = ' ';
int end = 1, i = 0;
long seek = 0;
FILE* vp = NULL;
FILE* sp = NULL;
//Open th5e files.
vp = fopen(virus_address, "rb");
sp = fopen(scaned_address, "rb");
fseek(vp, 0, SEEK_SET);
fseek(sp, 0, SEEK_SET);
//pre scanning
seek = 0;
//Check if the file infected.
while (!(feof(sp)) && end)
{
fread(&s, 1, 1, sp);
if (v == s)
{
v = fgetc(vp);
}
else
{
seek++;
fseek(vp, 0, SEEK_SET);
fseek(sp, seek, SEEK_SET);
fread(&v, 1, 1, vp);
}
if (v == EOF)
{
end = 0;
}
}
fclose(vp);
fclose(sp);
return end;
}
答案 0 :(得分:3)
fseek
的手册页说:
成功调用fseek()函数会清除文件结束指示符
当你的程序循环时,在fseek(sp, seek, SEEK_SET);
之前调用feof(sp)
,这就是feof
总是返回0的原因。并且因为你没有测试fread(&s, 1, 1, sp);
的返回值你的程序循环永远。