In this tutorial, you'll learn how to merge multiple text files into a single output file using the C programming language. This is a common task when combining logs, stitching together reports, or consolidating data from several sources. The program opens the destination file in write mode, then opens each source file in read mode and copies its contents line by line into the destination. Order matters — the source files are merged in the order you specify.
📝 Problem Statement
Write a program in C to merge multiple text files into a single text file.
⚙️ How the Program Works
The program follows a "write-once, read-many" pattern:
- Ask for the destination filename (or hard-code it as
merged.txt). - Ask for the list of source filenames — or accept them as command-line arguments.
- Open the destination with
fopen("merged.txt", "w"). This creates or truncates the output file. - For each source file: open it in read mode, copy its contents line by line with
fgets()/fputs(), then close it. - Close the destination when all sources have been copied.
💻 Complete C Program
#include <stdio.h>
#include <stdlib.h>
#define BUFSIZE 1024
#define MAX_FILES 10
int main(void)
{
FILE *dest, *src;
char dest_name[100];
char src_name[100];
char line[BUFSIZE];
int n, i;
printf("Enter the output filename: ");
scanf("%99s", dest_name);
printf("How many files to merge? ");
scanf("%d", &n);
if (n < 1 || n > MAX_FILES)
{
printf("Invalid number of files (1-%d).\n", MAX_FILES);
return 1;
}
/* Open the destination in write mode */
dest = fopen(dest_name, "w");
if (dest == NULL)
{
printf("Error: Could not create '%s'.\n", dest_name);
return 1;
}
for (i = 0; i < n; i++)
{
printf("Enter source filename #%d: ", i + 1);
scanf("%99s", src_name);
src = fopen(src_name, "r");
if (src == NULL)
{
printf("Warning: Skipping '%s' (could not open).\n", src_name);
continue;
}
/* Copy every line from src into dest */
while (fgets(line, BUFSIZE, src) != NULL)
{
fputs(line, dest);
}
fclose(src);
printf(" Merged '%s' into '%s'.\n", src_name, dest_name);
}
fclose(dest);
printf("\nAll files merged into '%s'.\n", dest_name);
return 0;
}🖥️ Sample Output
Assume two input files exist:
file1.txt:
Line 1 from file1Line 2 from file1
file2.txt:
Line 1 from file2Line 2 from file2
Running the program:
How many files to merge? 2
Enter source filename #1: file1.txt
Merged 'file1.txt' into 'merged.txt'.
Enter source filename #2: file2.txt
Merged 'file2.txt' into 'merged.txt'.
All files merged into 'merged.txt'.
After the program finishes, merged.txt contains:
merged.txt:
Line 1 from file1Line 2 from file1
Line 1 from file2
Line 2 from file2
🔍 Line-by-Line Explanation
| Line / Code | Explanation |
|---|---|
#define BUFSIZE 1024 |
Size of the line buffer. 1024 bytes handles typical text lines comfortably. |
fopen(dest_name, "w") |
Opens the output file for writing. Existing content is truncated — if you want to preserve existing content, use "a". |
for (i = 0; i < n; i++) |
Iterates over the source files one at a time. |
fopen(src_name, "r") |
Opens the current source file for reading. |
if (src == NULL) { ... continue; } |
If a source file can't be opened, skip it and move on to the next one — the merge still completes for the other files. |
while (fgets(line, BUFSIZE, src) != NULL) |
Reads one line at a time from the source until end of file. |
fputs(line, dest) |
Writes the line — including its trailing newline — to the destination. |
fclose(src) |
Closes the current source file before opening the next one. |
fclose(dest) |
Closes the destination after all files are merged. The output is fully written only after this call. |
"w", so any existing content in merged.txt is erased. If you want to append to a merged file that already exists, change the mode to "a" — everything else stays the same.
🔁 Common Variations
The core pattern — open destination, loop over sources, copy, close — adapts easily to several real-world scenarios:
| Variation | Change needed |
|---|---|
| Merge files given as command-line arguments | Use int main(int argc, char *argv[]), treat argv[1] as the destination and argv[2..] as sources. |
| Merge in binary mode | Open with "rb" / "wb" and use fread/fwrite instead of fgets/fputs. |
| Append to an existing destination | Change "w" to "a" on the destination. |
Merge all .txt files in a directory |
Iterate over directory entries with opendir/readdir (POSIX) or FindFirstFile (Windows). |
| Skip empty source files | Track whether any characters were read; print a note if the source was empty. |
🐛 Common Pitfalls
- Losing the newline at the end of a source file: If a source file doesn't end with a newline,
fgetsreturns its last line without one. The next source's first line will then be glued to the same line in the destination. To fix, check the last character of every line and add'\n'if missing. - Leaking source handles: If the program exits the loop early (for example, on
continue), ensurefcloseis still called on any open files. The current version is safe becausecontinueonly fires whensrcis alreadyNULL. - Silently overwriting the destination: Using
"w"on an existing file destroys its content. If that wasn't the intent, prompt for confirmation or use"a". - Buffer too small: If a line is longer than 1023 characters,
fgetsreturns it in chunks. The merge still works — but each chunk becomes a separate line in the output. - Merging a file into itself: If the user accidentally lists the destination as one of the sources, the output will be corrupted. Add a check: if
strcmp(src_name, dest_name) == 0, skip that file.
💡 Tips & Best Practices
- Validate that
nis within a reasonable range before allocating or looping — theMAX_FILESguard prevents misuse. - Print progress after each source file is merged so the user knows the program isn't stuck.
- Consider adding a separator between merged files (e.g.,
fputs("--- end of file ---\n", dest)) if that helps readability. - Compile with
gcc -Wall -Wextra -std=c11 -gto catch unused variables and format-string mismatches. - On Windows, if the source files were created on Unix,
fgetsin text mode still converts\ncorrectly — the merge is portable.