-
Comparing two files
Can someone tell me why isn't my code working?
Code:
#include <stdio.h>
#include <stdlib.h>
int main ()
{
FILE *f1;
FILE *f2;
char c1, c2;
int cmp;
f1 = fopen("file1.txt", "r");
f2 = fopen("file2.txt", "r");
if (f1 == NULL || f2 == NULL)
{
printf("File access error.\n");
exit(1);
}
else
{
while (fgetc(f1) != EOF || fgetc(f2) != EOF)
{
c1 = fgetc(f1);
c2 = fgetc(f2);
if (c1 != c2)
{
printf("CODE 1: Files are not equal.\n");
cmp = 1;
break;
}
}
if (cmp == 0)
printf("CODE 0: Files are equal.\n");
}
if (fclose(f1) != 0 || fclose(f2) != 0)
printf("File close error.\n");
return 0;
}
-
Define "not working". That's a pretty ridiculous way to ask for help. We're not standing over your shoulder looking at the output.
I will say this:
Code:
while (fgetc(f1) != EOF || fgetc(f2) != EOF)
That's not the right way to do it. For one thing, you're throwing away a character from f1 with each loop.
-
The program only does one thing, so basically it doesn't do the only thing it's supposed to do, which is comparing files. It keeps telling me the files are not equal even if I copy pasted the files used.
I don't really understand what you mean. I meant for the loop to stop once a file reaches the EOF.
-
It's because of EXACTLY what I said.
Code:
while (fgetc(f1) != EOF || fgetc(f2) != EOF)
That first does an fgetc on the file f1 and THROWS away the result. If it's not EOF, then the second half of that OR does not get executed due to short circuiting (if the first statement in an OR is true, what's the point of evaluating the second, right? It's this OR that, and if this is true it doesn't matter whether that is true, because the OR condition is satisfied).
f1 now is pointing at the second character in the file, while f2 is pointing at the first.
-
Ah, I didn't realize you literally meant it to be thrown away. I thought it was increasing the sequence. Sorry, my bad.
I think I got it. I changed the middle part to this:
Code:
else
{
while (1)
{
c1 = fgetc(f1);
c2 = fgetc(f2);
if (c1 != c2)
{
printf("CODE 1: Files are not equal.\n");
break;
}
else if (c1 == EOF || c2 == EOF)
{
printf("CODE 0: Files are equal.\n");
break;
}
}
}
I'm still checking if the algorithm works correctly, but in the meantime, thanks for the help!
-
c1 and c2 should be of type int, not char, because fgetc returns and int and EOF is a negative value of type int.
-
Ah, I didn't know that fgetc returns an int. Thanks, I checked and you're right. Strangely, the program works as is and my lecturer actually declares it as char. Any idea why?
-
The only reason fgetc is defined as returning an integer is because EOF is defined as a negative integer. Signed char happens to store small negative integers. I have not seen an implementation that breaks if you use char, but that doesn't make it right.