C Program to Compare two Text or Data files
⦁ The C library function char *gets(char *str) reads a line from stdin and stores it into the string pointed to by str.
⦁ getc( ) returns a character from the specified file.
--------------------------------------------------------------------------------------------------------------------------
#include<stdio.h>
int main( )
{
FILE *fp1, *fp2;
int ch1,ch2;
char fname1[40],fname2[40];
printf("Enter name of first file:");
gets(fname1);
printf("Enter name of second file:");
gets(fname2);
fp1 = fopen(fname1, "r");
fp2 = fopen(fname2, "r");
if(fp1 == NULL){
printf("Cannot Open %s for reading",fname1);
exit(1);
} else if (fp2 == Null){
printf("Cannot Open %s for reading ",fname2);
exit(1);
}else{
ch1 = getc(fp1);
ch2 = getc(fp2);
while ((ch1 != EOF) && (ch2 != EOF) && (ch1 == ch2)){
ch1 = getc(fp1);
ch2 = getc(fp2);
}
if(ch1 == ch2)
printf("Files are Identical n");
else if (ch1 != ch2)
printf("Files are not Identical n");
fclose(fp1);
fclose(fp2);
}
return(0);
}
--------------------------------------------------------------------------------------------------------------------------
Explanation
--------------------------------------------------------------------------------------------------------------------------
⦁ Declare two file pointers for two files.
⦁ Open two files in Read mode.
⦁ Inside while loop read both files character by character
⦁ Check both characters whether they are equal or not
⦁ If inside if statement ch1 = EOF and ch2 = EOF then both files are said to be equal.
⦁ Otherwise both files are not equal.
EmoticonEmoticon