Reputation: 1
I need to check if the content of the two files is the same, I mean if the string in each file is equal to each other. I wrote a program in c language with a function that if the files are the same will return 2 otherwise return 1. My problem is that the function keeps return 1 no matter what is the content.
#include <stdio.h>
int compareFilles(FILE *fp1, FILE *fp2){
int word1 = getc(fp1);
int word2 = getc(fp2);
//A loop until the end of the files(EOF)
while (word1 =! EOF && word2 != EOF && word1 == word2){
word1 = getc(fp1);
word2 = getc(fp2);
}
if (word1 != word2){
return 1;
}else{
return 2;
}
}
int main(int argc, char* argv[]){
FILE *fp1 = fopen(argv[0], "r");
FILE *fp2 = fopen(argv[1], "r");
printf("%d", compareFilles(fp1, fp2));
//closing the files
fclose(fp1);
fclose(fp2);
return 0;
}
Upvotes: 0
Views: 266
Reputation: 41686
#include <stdio.h>
int compareFilles(FILE *fp1, FILE *fp2){
This function should return a bool
since that is the natural data type for expressing a true/false
value.
int word1 = getc(fp1);
int word2 = getc(fp2);
The variable names are wrong. The getc
function does not read a word, it only reads a single byte from a file.
//A loop until the end of the files(EOF)
while (word1 =! EOF && word2 != EOF && word1 == word2){
As said in one of the comments, the =!
means "assign negative" instead of the "unequal" you meant. To avoid this kind of mistakes in the future, always let an automatic code formatter format your code before it is saved to disk. Then that code would have been shown as word1 = !EOF
, which should draw enough attention. Doing this will also protect you from the famous goto fail bug, which means you will have a better programming standard than Apple. That sounds like a lot, doesn't it?
Plus, always enable all compiler warnings. The compiler would have warned you about an "assignment in a condition, which is often not intended", which is exactly the case here.
word1 = getc(fp1);
word2 = getc(fp2);
}
if (word1 != word2){
return 1;
}else{
return 2;
}
}
If your function returns bool
, that last if
statement should simply be replaced with return word1 == word2
.
int main(int argc, char* argv[]){
FILE *fp1 = fopen(argv[0], "r");
FILE *fp2 = fopen(argv[1], "r");
The error checking is missing here. If either of fp1
or fp2
is NULL, the program must handle this error.
printf("%d", compareFilles(fp1, fp2));
//closing the files
fclose(fp1);
fclose(fp2);
return 0;
}
Upvotes: 1
Reputation: 224310
Generally, argv[0]
contains the command used to start the program, usually the name of the executable file or part of it. Thus, your program is comparing its own executable file to the file named by the first argument (argv[1]
), and they are different.
Upvotes: 1