【问题标题】:Search a part of a file in another file在另一个文件中搜索文件的一部分
【发布时间】:2015-05-29 17:04:21
【问题描述】:

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

请帮我修复我的代码。

【问题讨论】:

  • 解释你的代码有什么问题
  • 你到底有什么问题?
  • 程序运行不正常。它总是返回 0 而不是应该返回的 1。
  • while (((result2=fread(virus_buffer,1,sizeof(char),virus))>0)&&flag==1),我觉得你需要把flag==1从这里去掉,这里需要改一下逻辑
  • 你在很大程度上过于复杂了。为什么不直接将整个文件读入内存然后使用memmem()(或者循环加上memcmp(),如果它不可用)来查找针的位置?

标签: c file-io


【解决方案1】:

这比它需要的要复杂得多。使用 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()'ing haystack 文件。

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-07-28
  • 2013-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-10
  • 1970-01-01
相关资源
最近更新 更多