C program to compare two files and report mismatches
Last Updated :
17 May, 2017
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.
Examples:
Input :
file1.txt contains
it is
fun
file2.txt contains
it is
run
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.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void compareFiles( FILE *fp1, FILE *fp2)
{
char ch1 = getc (fp1);
char ch2 = getc (fp2);
int error = 0, pos = 0, line = 1;
while (ch1 != EOF && ch2 != EOF)
{
pos++;
if (ch1 == '\n' && ch2 == '\n' )
{
line++;
pos = 0;
}
if (ch1 != ch2)
{
error++;
printf ( "Line Number : %d \tError"
" Position : %d \n" , line, pos);
}
ch1 = getc (fp1);
ch2 = getc (fp2);
}
printf ( "Total Errors : %d\t" , error);
}
int main()
{
FILE *fp1 = fopen ( "file1.txt" , "r" );
FILE *fp2 = fopen ( "file2.txt" , "r" );
if (fp1 == NULL || fp2 == NULL)
{
printf ( "Error : Files not open" );
exit (0);
}
compareFiles(fp1, fp2);
fclose (fp1);
fclose (fp2);
return 0;
}
|
Output:
Line Number : 2 Error Position : 1
Total Errors : 1
Share your thoughts in the comments
Please Login to comment...