C PROGRAMMING PROGRAM • FILE HANDLING
Merge Two Text Files
Learn how to merge two text files using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
Alpha Beta
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("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;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Alpha Beta
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Copy the complete first stream followed by the complete second stream into a new file.
- 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.
