C program for comparing two files

C program for comparing two files:
If you are using any software then below program will not give an error, but if you are using TURBO C then you have to make some changes like: void main() and some function like clrscr() or getch().

#include<stdio.h>
main()
{
   FILE *fp1,*fp2;
   int ch1,ch2;
   char fname1[40],fname2[40];

   printf("Enter first file name:");
   gets(fname1);

   printf("Enter second file name:");
   gets(fname2);

   fp1 = fopen(fname1,"r");
   fp2 = fopen(fname2,"r");

   if(fp1 == NULL)
    {
      printf("Cannot open %s for reading ",fname1);
    }
   else if(fp2 == NULL)
    {
      printf("Cannot open %s for reading ",fname2);
    }
   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 Same");
      else if(ch1 != ch2)
         printf("Files are Not Same");

      fclose(fp1);
      fclose(fp2);
   }
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.