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

C 在另一个文件中搜索文件的一部分,c,file-io,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(fi

这是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;
}

请帮我修复代码。

这比需要的复杂得多。使用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
intfd=open(“/path/to/haystack/file”,仅限O_RDONLY);
结构统计某人;
财政司司长(财务司司长及财务司司长);
char*haystack=mmap(NULL,sb.st_size,PROT_READ,MAP_PRIVATE,fd,0);
关闭(fd);
//needleSize是“指针”的字节数
尺寸=sb.st\U尺寸-针头尺寸;
char*found=NULL;
用于(尺寸=0UL;ii
在搜索循环之后,我停止了所有的错误检查和
munmap()
'haystack文件


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

解释您的代码出了什么问题确切地说,您的问题是什么?程序运行不好。当它应该返回时,它总是返回0而不是1。
而((result2=fread(virus\u buffer,1,sizeof(char),virus))>0)和&flag==1)
,我认为您需要从这里删除标志==1,您需要更改此处的逻辑您正在大量地将其过度复杂化。为什么不将整个文件读入内存,然后使用
memmem()
(或循环加
memcmp()
,如果不可用)来查找指针的位置?Windows具有
CreateFileMapping()
.MS文档:示例: