C Programming
Computer Programming

C file handling program to compare contents of two files



Write C file handling program to compare contents of two files

\* C file handling program to compare contents of two files *\

# include < stdio.h >
# include < string.h >
# include < stdlib.h >
int   main( int argc, char *argv[] )
{

FILE *fp1 ;
FILE *fp2 ;
char filename1[20], filename2[20] ;
int cnt1 = 0 ;
int cnt2 = 0 ;
int flg = 0 ;

printf("\n Enter the first filename : ") ;
scanf("%s", filename1) ;
fp1 = fopen(filename1, "r") ;
if (fp1 == NULL)
{
      printf(" Cannot open first file ! \n") ;
      exit(0);
}

// move file pointer to end and get total number of bytes
fseek( fp1, 0, SEEK_END ) ;
cnt1 = ftell(fp1) ;

printf("\n Enter the second filename : ") ;
scanf("%s", filename2) ;
fp2 = fopen( filename2, "r") ;
if (fp2 == NULL)
{
      printf(" Cannot open second file ! \n") ;
      exit(0) ;
}

// move file pointer to end and get total number of bytes
fseek(fp2,0,SEEK_END) ;
cnt2 = ftell(fp2) ;

fseek(fp1,0,SEEK_SET) ;
fseek(fp2,0,SEEK_SET) ;

// check for the total number of bytes
if( cnt1 != cnt2 )
{
      printf("\n File contents are not same\n") ;
}
else
{
      while( ! feof(fp1) )
      {
            if( fgetc(fp1) != fgetc(fp2) )
            {
                  flg = 1 ;
                  break ;
            }
      }

      if( flg )
            printf("\n File contents are not same.\n") ;
      else
            printf("\n File contents are same.\n") ;
}

fclose(fp1) ;
fclose(fp2) ;
return 0 ;

}

Output of Program :

Output of C file handling program to compare contents of two files