C program to compare two files

      Two files are compared by checking each and every character of one file against the other file. This program compare two files in c checks this with help of while loop which iterates until either it reaches end of one file or some mismatch with characters in the files. By the end of while loop if it does not found any mismatch then two files are identical otherwise not.

compare two files in c



Source Code to compare two files in c

#include<stdio.h> 
#include<stdlib.h> 
int main() 
{ 
	FILE *fp1, *fp2; 
	int ca, cb; 
	char fname1[40], fname2[40]; 
	printf("Enter first filename:"); 
	fflush(stdin); 
	gets(fname1);              //Step 1
	printf("Enter second filename:"); 
	fflush(stdin); 
	gets(fname2);            // Step 1
	fp1 = fopen(fname1, "r"); //Step 2
	/* open first file for reading */ 
	fp2 = fopen(fname2, "r");  //Step 2
	if(fp1 == NULL) 
	{ 
		printf("Cannot open the file %s for reading \n", fname1); 
		exit(1); 
	} 
	else if(fp2 == NULL) 
	{ 
		printf("Cannot open %s for reading \n", fname2); 
		exit(1); 
	} 
	else  
	{ 
		ca = getc(fp1); 
		cb = getc(fp2); 
		while(ca != EOF && cb != EOF && ca == cb)  //Step 3 
		{ 
			ca = getc(fp1); 
			cb = getc(fp2); 
		} 
		if(ca == cb)                   //Step 4
		  printf("Files are identical \n"); 
		else if(ca != cb) 
		  printf("Files differ \n"); 
		fclose(fp1); 
	fclose(fp2); 
} 
return 0; 
} 


edit-code-image

Sample Test cases:

1.  Enter first filename  : 1.txt
    Enter second filename : 2.txt
    Files are identical

2.  Enter first filename  : 1.txt
    Enter second filename : 3.txt
    Cannot open 3.txt for reading

3.  Enter first filename  : 1.txt
    Enter second filename : 2.txt
    Files differ

Explanation:

Step 1: The file names which has to be compared are read from the user using gets() function.

Step 2: These two files are opened using the fopen() function which returns the function pointer corresponding to that file.

Step 3: This while loop checks every character of one file against the every character of other file. If their is a mismatch it will come out of the loop.

Step 4: Finally after exit from the loop if the characters of two files are equal then those two files are identical otherwise not.

More Content: ToPoint
More about C Programming : C Programming