Question

My program runs as it should - prints out appropriate values but it will not terminate automatically unless I suspend (ctrl z) it? Where's the issue?

void compare_two_binary_files(FILE *f1, FILE *f2)
{
    unsigned char ch1, ch2;
    int flag = 0;
    int count = 0;
    while (((ch1 = fgetc(f1)) != EOF) &&((ch2 = fgetc(f2)) != EOF)){
            if (ch1 != ch2){
                    printf("Byte pos where two files differ is: %d\n", count + 1);
                    printf("byte value of file 1:  %o\n", ch1);
                    printf("byte value of file 2: %o\n", ch2);
            }
            count++;
    }
}
Était-ce utile?

La solution

fgetc returns an int, not an unsigned char. EOF is an int as well. Change ch1 and ch2 to ints and it should work.

What's happening is that fgetc is returning -1 (the value of EOF) but you are stuffing that into an unsigned char, only getting the low 8 bits (all 1's). Then, in order to compare this value to EOF, the unsigned char is extended to an int by adding 0's on the left. This will not be equal to EOF, so it never stops.

A little more:

In 32 bits, -1 is 0xFFFFFFFF. Stuffing that into an unsigned (or signed) char gives 0xFF. When it's extended for comparison, since it's an unsigned char, it's extended like this 0x000000FF, which does not equal 0xFFFFFFFF. A signed char would be extended to 0xFFFFFFFF, but it's still not a good idea to use a char since then you can't tell the difference between the end-of-file sentinel and a 0xFF byte.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top