C program to compare two files and report mismatches

We are given almost two identical files. But some characters are corrupted. We need to find the line number and their position where those corrupted letter exists as well as Total number of corrupted (error) letters.


Input :
file1.txt contains
it is
file2.txt contains
it is

Output :
Line Number : 2         Error Position : 1
Total Errors : 1

Prerequisite : getc() in C

Steps :
1.> Open two file using File pointer in read only mode.
2.> Fetch data of file in two char variable one by one until end of file.
3.> If variable encounter new line then increment line number and reset position to zero.
4.> If variables are not equal then increment number of error and print error line as well as error index.





// C program to compare two files and report
// mismatches by displaying line number and
// position of line.
void compareFiles(FILE *fp1, FILE *fp2)
    // fetching character of two file
    // in two variable ch1 and ch2
    char ch1 = getc(fp1);
    char ch2 = getc(fp2);
    // error keeps track of number of errors
    // pos keeps track of position of errors
    // line keeps track of error line
    int error = 0, pos = 0, line = 1;
    // iterate loop till end of file
    while (ch1 != EOF && ch2 != EOF)
        // if both variable encounters new
        // line then line variable is incremented
        // and pos variable is set to 0
        if (ch1 == '\n' && ch2 == '\n')
            pos = 0;
        // if fetched data is not equal then
        // error is incremented
        if (ch1 != ch2)
            printf("Line Number : %d \tError"
               " Position : %d \n", line, pos);
        // fetching character until end of file
        ch1 = getc(fp1);
        ch2 = getc(fp2);
    printf("Total Errors : %d\t", error);
// Driver code
int main()
    // opening both file in read only mode
    FILE *fp1 = fopen("file1.txt", "r");
    FILE *fp2 = fopen("file2.txt", "r");
    if (fp1 == NULL || fp2 == NULL)
       printf("Error : Files not open");
    compareFiles(fp1, fp2);
    // closing both file
    return 0;



Line Number : 2         Error Position : 1
Total Errors : 1

This article is contributed by Aditya Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

My Personal Notes arrow_drop_up

Article Tags :
Practice Tags :


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.