0
votes

I'm trying to read characters from a binary file and compare them to characters from another binary file, but I want to start reading one of the files from the middle, not the beginning. When I try it, I can't read the file I'm trying to read from the middle because it immediately returns EOF. I tried to read it from different points, even moving the stream just a single place but it still returned EOF straight away.

int scanWithOffset(FILE* fc, FILE* fv, int start, int end)
{
    int charRead1 = 0, charRead2 = 0, matchCounter = 0, match = 0;
    int fileSize = findFileSize(fv);
    int counter = 0;

    if (!fseek(fc, start, SEEK_SET))
    {
        while (((charRead2 = fgetc(fv)) != EOF) && ((charRead1 = fgetc(fc)) != EOF)
               && !match && counter < (end - start))
        {
            counter++;
            if (charRead1 == charRead2)
            {
                matchCounter++;
                if (matchCounter == fileSize)
                {
                    match = 1;
                    fclose(fc);
                }
            }
            else
            {
                // if something doesn't match up, reset the counter and bring
                // the stream back to the beginning
                matchCounter = 0; 
                fseek(fv, 0, SEEK_SET);
            }
        }

        if (!match)
        {
            fclose(fc);
        }
    }

    return match;
}
1
Does is work if you drop the fseek alltogether? - Jabberwocky
It does work if I drop it, but I still need to read it from a certain part of the file, I can't just read it from the beginning to the end. I also fixed the typo and it did not help. - Egor Matuk
What happens if you call scanWithOffset with start = 0? - Jabberwocky
If I do that it works. - Egor Matuk
verify which file operation triggered the EOF signal. Could potentialy be either fgetc(fc) or fgetc(fv)... maybe print ferror(fv)? - pmg

1 Answers

0
votes
if (matchCounter == fileSize)
{
   match = 1;
   fclose(fc);
}

You do not break the while loop after closing fc. You have to exit the while loop when you reach matchCounter == fileSize. You can add break; after fclose(fc):

if (matchCounter == fileSize)
{
   match = 1;
   fclose(fc);
   break;
}