Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C program to compare two files and report mismatches
In C programming, we can access files and read their content to perform various operations. Comparing two files character by character helps identify differences between similar documents.
This program compares two text files and reports any mismatches found, including the line number and position where the first difference occurs.
Syntax
FILE *fopen(const char *filename, const char *mode); int getc(FILE *stream); int fclose(FILE *stream);
Algorithm
- Step 1: Open both files with read mode
- Step 2: Read characters one by one from both files simultaneously
- Step 3: Compare characters and track line numbers and positions
- Step 4: Report mismatches with their locations
- Step 5: Close both files
Note: This example requires two text files named "file1.txt" and "file2.txt" in the same directory. Create these files with slightly different content before running the program.
Example
Here's a complete program that compares two files and reports mismatches −
#include <stdio.h>
#include <stdlib.h>
void compareFiles(FILE *file1, FILE *file2) {
char ch1 = getc(file1);
char ch2 = getc(file2);
int error = 0, pos = 0, line = 1;
while (ch1 != EOF && ch2 != EOF) {
pos++;
if (ch1 == '
' && ch2 == '
') {
line++;
pos = 0;
}
if (ch1 != ch2) {
error++;
printf("Line Number: %d \tError Position: %d
", line, pos);
}
ch1 = getc(file1);
ch2 = getc(file2);
}
printf("Total Errors: %d
", error);
}
int main() {
FILE *file1 = fopen("file1.txt", "r");
FILE *file2 = fopen("file2.txt", "r");
if (file1 == NULL || file2 == NULL) {
printf("Error: Files not found or cannot be opened
");
return 1;
}
compareFiles(file1, file2);
fclose(file1);
fclose(file2);
return 0;
}
Sample Input Files
file1.txt:
Hello! Welcome to tutorials Point
file2.txt:
Hello! Welcome to tutorials point
Output
Line Number: 2 Error Position: 20 Total Errors: 1
Key Points
- The program reads files character by character using
getc() - Line numbers increment when newline characters are encountered
- Position counter resets to 0 at the beginning of each new line
- Always check if files open successfully before processing
- Close files properly using
fclose()to free resources
Conclusion
This file comparison program efficiently identifies character-level differences between two text files. It provides precise location information for mismatches, making it useful for text validation and difference detection tasks.
