About Me

My photo
Raipur, Chhattisgarh, India
Hi , I am Amit Thakur. I have worked as a QA Engineer for two years and as a Java Developer for one year in NIHILENT TECHNOLOGIES PVT. LTD., Pune.Currently I am working as DEAN (Research & Development) in Bhilai Institute of Technology, Raipur.

Tuesday, September 3, 2013

C Program to Compare two Text or Data files

Program : C Program to Compare two text/data files in C Programming

  • Check whether two files are identical or not.
#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 :

  1. Firstly Declare two file pointers for two files.
  2. Open two files in read mode.
  3. Now Inside while loop read both files character by character.
  4. Check both characters whether they are equal or not.
  5. If inside if statement ch1 = EOF and ch2=EOF then both files are said to be equal otherwise both files are non identicle.

No comments: