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.

Intermediatefgetc()EOFFile comparison

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
Files are identical.

COMPLETE C PROGRAM

Complete C implementation

compare-two-text-files.c
Open in compiler
#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;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

Files are identical.
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Read corresponding characters until they differ or both streams reach the end together.
  3. 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.