📁📚Intermediate

Compare Two Files and Report Mismatches

File comparison

Compare two files and report mismatches.

Program Code

compare_files.c
C
1#include <stdio.h>
2
3int main() {
4 FILE *file1 = fopen("file1.txt", "r");
5 FILE *file2 = fopen("file2.txt", "r");
6
7 if (!file1 || !file2) {
8 printf("Error opening files!\n");
9 return 1;
10 }
11
12 int ch1, ch2;
13 int line = 1, col = 0;
14 int differences = 0;
15
16 while (1) {
17 ch1 = fgetc(file1);
18 ch2 = fgetc(file2);
19 col++;
20
21 if (ch1 == '\n') {
22 line++;
23 col = 0;
24 }
25
26 if (ch1 != ch2) {
27 if (ch1 == EOF) {
28 printf("File 1 is shorter\n");
29 break;
30 } else if (ch2 == EOF) {
31 printf("File 2 is shorter\n");
32 break;
33 } else {
34 printf("Mismatch at line %d, col %d: '%c' vs '%c'\n",
35 line, col, ch1, ch2);
36 differences++;
37 }
38 }
39
40 if (ch1 == EOF && ch2 == EOF) break;
41 }
42
43 if (differences == 0) {
44 printf("Files are identical!\n");
45 } else {
46 printf("Total differences: %d\n", differences);
47 }
48
49 fclose(file1);
50 fclose(file2);
51
52 return 0;
53}
Output

Mismatch at line 2, col 5: 'a' vs 'b'

Mismatch at line 3, col 1: 'X' vs 'Y'

Total differences: 2

Want to Learn More?

Explore our comprehensive tutorials for in-depth explanations of C programming concepts.

Browse Tutorials
Back to All Examples