C PROGRAMMING PROGRAM • FILE HANDLING
Compare Two Text Files Character by Character
Learn how to compare two text files character by character using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
Files are identical.
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
int main(void)
{
FILE *first = fopen("first.txt", "w");
FILE *second = fopen("second.txt", "w");
if (first == NULL || second == NULL) return 1;
fputs("CodeBhavya\n", first); fputs("CodeBhavya\n", second);
fclose(first); fclose(second);
first = fopen("first.txt", "r"); second = fopen("second.txt", "r");
if (first == NULL || second == NULL) return 1;
int left, right;
do {
left = fgetc(first); right = fgetc(second);
if (left != right) break;
} while (left != EOF);
puts(left == right ? "Files are identical." : "Files are different.");
fclose(first); fclose(second);
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Files are identical.
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Read corresponding characters until they differ or both streams reach the end together.
- Display the computed result.
Read corresponding characters until they differ or both streams reach the end together.
EFFICIENCY
Time and space complexity
Time complexity
O(min(n,m))
Auxiliary space
O(1)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
