0

This is part of a C code. I need help to fix it. This program checks if a file signature is in another file. If it is, the function finds match then it returns 1 else it returns 0.

The problem is that it always returns 0 even when it should return 1.

This is the function I wrote:

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

Please help me fix my code.

uriburg
  • 19
  • 5

1 Answers1

0

That is much more complicated than it needs to be. With a 64-bit binary, mmap() the file then use memcmp() to search its contents:

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

I left off all error checking and munmap()'ing the haystack file after the search loop.

If you're limited to a 32-bit binary, to handle arbitrarily large files you need to do something more complicated, but nowhere near as complicated as the code you posted. You can use rolling mmap() calls, for example, munmap()'ing data you've already searched through so you don't use too much memory for a 32-bit process.

Andrew Henle
  • 32,625
  • 3
  • 24
  • 56
  • Windows has `CreateFileMapping()`. MS documentation: https://msdn.microsoft.com/en-us/library/windows/desktop/aa366537%28v=vs.85%29.aspx Example: http://stackoverflow.com/questions/19849400/how-to-createfilemapping-in-c – Andrew Henle May 24 '15 at 18:27