在另一个文件中搜索文件的一部分

时间:2015-05-21 12:22:29

标签: c file-io

这是C代码的一部分。我需要帮助来解决它。 该程序检查文件签名是否在另一个文件中。 如果是,则函数找到匹配,然后返回1,否则返回0

问题是,即使它应该返回0,它也始终返回1

这是我写的函数:

int scanFile(char* file_name, FILE * virus_signature, long virus_size) //Scan the given file to see if he has the signature
{
FILE * file_for_scan = fopen(file_name, "rb");
char ch_temp, ch_temp2;
int i = 0;
fseek(virus_signature, 0, SEEK_SET);
while ((ch_temp = fgetc(file_for_scan)) != EOF)
{
    if ((ch_temp2=fgetc(virus_signature)) == ch_temp)
    {
        i++;
        if (i == virus_size)
        {
            fclose(file_for_scan);
            return 1;
        }
    }
    else
    {
        i = 0;
        fseek(virus_signature, 0, SEEK_SET);
    }

}
fclose(file_for_scan);
return 0;
}

请帮我修改我的代码。

1 个答案:

答案 0 :(得分:0)

这比它需要的要复杂得多。使用64位二进制文​​件mmap(),然后使用memcmp()搜索其内容:

int fd = open( "/path/to/haystack/file", O_RDONLY );
struct stat sb;
fstat( fd, &sb );
char *haystack = mmap( NULL, sb.st_size, PROT_READ, MAP_PRIVATE, fd, 0 );
close( fd );

// needleSize is how many bytes the "needle" is
size_t bytesToSearch = sb.st_size - needleSize;
char *found = NULL;
for( size_t ii = 0UL; ii < bytesToSearch; ii++ )
{
    if (!memcmp( haystack + ii, needle, needleSize )
    {
        found = haystack + ii;
        break;
    }
}
// if found is non-NULL, it points to where the needle is

在搜索循环之后,我停止了所有错误检查和munmap()“haystack文件”。

如果您仅限于32位二进制文​​件,要处理任意大的文件,您需要做一些更复杂的事情,但远不及您发布的代码那么复杂。您可以使用滚动mmap()来电,例如,munmap()您已搜索过的数据,这样您就不会为32位进程使用太多内存