This blog is under construction

Monday, 29 July 2013

C program to compare two files character by character

Write a C program to compare two files character by character.


  #include <stdio.h>
  #include <string.h>
  #define MAX 256

  int main() {
        int ch1, ch2;
        FILE *fp1, *fp2;
        char fname1[MAX], fname2[MAX];

        /* get the first input file from the user */
        printf("Enter your first file name:");
        fgets(fname1, MAX, stdin);
        fname1[strlen(fname1) - 1] = '\0';

        /* get the second input file from the user */
        printf("Enter your second file name:");
        fgets(fname2, MAX, stdin);
        fname2[strlen(fname2) - 1] = '\0';

        /* open the first file in read mode */
        fp1 = fopen(fname1, "r");

        /* error handling */
        if (!fp1) {
                printf("Unable to open the file %s!!\n", fname1);
                return 0;
        }

        /* open the second input file in read mode */
        fp2 = fopen(fname2, "r");

        /* error handling */
        if (!fp2) {
                printf("Unable to open the file %s!!\n", fname2);
                return 0;
        }

        /* checking whether the contents of both the i/p files are same */
        while (!feof(fp1)  || !feof(fp2)) {
                ch1 = fgetc(fp1);
                ch2 = fgetc(fp2);

                if (ch1 != ch2) {
                        /* printing the result */
                        printf("Contents in both files are not same!!\n");
                        /* closing the opened files */
                        fclose(fp1);
                        fclose(fp2);
                        return 0;
                }
        }

        /* print the result */
        printf("Contents of both the input files are same!!\n");

        /* closing the opened files */
        fclose(fp1);
        fclose(fp2);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ cat data.txt 
  Take up one idea. Make that one idea your life -
  think of it, dream of it, live on that idea. Let 
  the brain, muscles, nerves, every part of your 
  body, be full of that idea, and just leave every 
  other idea alone. This is the way to success.

  jp@jp-VirtualBox:~/$ cat output.txt   

  jp@jp-VirtualBox:~/$ ./a.out
  Enter your first file name:data.txt
  Enter your second file name:output.txt
  Contents in both files are not same!!

  jp@jp-VirtualBox:~/$ cp data.txt output.txt 

  jp@jp-VirtualBox:~/$ ./a.out
  Enter your first file name: data.txt
  Enter your second file name: output.txt
  Contents of both the input files are same!!






SEE ALSO

    No comments:

    Post a Comment