I need to compare 2 files and return 1 if they are same or 0 if not, but function always return 0. I have no idea why. Maybe you know diferent function that can do this.
int compare(char *file_1, char *file_2) { FILE *data_1 = fopen(file_1,"r"); FILE *data_2 = fopen(file_2,"r"); char line1[1000]; char line2[1000]; while(fgets(line1, sizeof(line1), data_1)&&fgets(line2, sizeof(line2), data_2)){ if(strcmp(line1,line2)==0){ fclose(data_1); fclose(data_2); return 0; } } fclose(data_1); fclose(data_2); return 1; }
Advertisement
Answer
strcmp(line1,line2)==0
means line1 and line2 are equals, your code supposes they are different
There is an other error, if a file is starts with the content of the other you consider the files are equals (supposing you corrected the strcmp)
I encourage you to check the result of the fopen in case at least one of them does not exist / cannot be open
a solution can be :
int compare(char *file_1, char *file_2) { FILE *fp1 = fopen(file_1,"r"); if (fp1 == 0) return 0; FILE *fp2 = fopen(file_2,"r"); if (fp2 == 0) { fclose(fp1); return 0; } char line1[1000]; char line2[1000]; char * r1, * r2; int result; for (;;) { r1 = fgets(line1, sizeof(line1), fp1); r2 = fgets(line2, sizeof(line2), fp2); if ((r1 == 0) || (r2 == 0)) { result = (r1 == r2); break; } if (strcmp(line1,line2) != 0) { result = 0; break; } } fclose(fp1); fclose(fp2); return result; }