This blog is under construction

Tuesday, 30 July 2013

C program to compare two files line by line

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


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

  int main() {
        FILE *fp1, *fp2;
        char file1[MAX], file2[MAX];
        char fline[MAX], sline[MAX];

        /* get the first input file name from the user */
        printf("Enter your first file name:");
        scanf("%s", file1);

        /* get the second input file name from the user */
        printf("Enter your second file name:");
        scanf("%s", file2);

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

        /* error handling */
        if (!fp1) {
                printf("Unable to open the first input file!!\n");
                return 0;
        }

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

        /* error handling */
        if (!fp2) {
                printf("Unable to open the second input file!!\n");
                fclose(fp1);
                return 0;
        }

        /* comparing two files line by line */
        while ((!feof(fp1)) || (!feof(fp2))) {
                fgets(fline, MAX, fp1);
                fgets(sline, MAX, fp2);

                /* if both the file contents are not equal */
                if (strcmp(fline, sline) != 0) {
                        printf("Given two files are not identical!!\n");
                        fclose(fp1);
                        fclose(fp2);
                        return 0;
                }
        }

        /* file contents in both files are same */
        printf("Given two file have identical contents!!\n");

        /* close the opened files */
        fclose(fp1);
        fclose(fp2);

        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ cat first.txt 
  abcdefghij
  0123456789
  abcdefghij
  0123456789
  abcdefghij
  0123456789

  jp@jp-VirtualBox:~/$ cat second.txt 
  0123456789
  abcdefghij
  0123456789
  abcdefghij
  0123456789

  jp@jp-VirtualBox:~/$ ./a.out
  Enter your first file name:first.txt
  Enter your second file name:second.txt
  Given two files are not identical!!






SEE ALSO

    No comments:

    Post a Comment