C PROGRAMMING PROGRAM • FILE HANDLING

Merge Two Text Files

Learn how to merge two text files using a clear C program.

IntermediateMultiple filesfgetc()Merge

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
Alpha
Beta

COMPLETE C PROGRAM

Complete C implementation

merge-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("Alpha\n", first); fputs("Beta\n", second);
    fclose(first); fclose(second);
    first = fopen("first.txt", "r"); second = fopen("second.txt", "r");
    FILE *merged = fopen("merged.txt", "w");
    if (first == NULL || second == NULL || merged == NULL) return 1;
    int character;
    while ((character = fgetc(first)) != EOF) fputc(character, merged);
    while ((character = fgetc(second)) != EOF) fputc(character, merged);
    fclose(first); fclose(second); fclose(merged);
    merged = fopen("merged.txt", "r");
    if (merged == NULL) return 1;
    while ((character = fgetc(merged)) != EOF) putchar(character);
    fclose(merged);
    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

Alpha
Beta
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Copy the complete first stream followed by the complete second stream into a new file.
  3. Display the computed result.

Copy the complete first stream followed by the complete second stream into a new file.

EFFICIENCY

Time and space complexity

Time complexity

O(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.