Merge Multiple Text Files — C File Handling Solution
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program to Merge Multiple Text Files into a Single Text File

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.

C program to merge multiple text files into a single text file using fopen, fgets, and fputs, with step-by-step explanation.

📝 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:

  1. Ask for the destination filename (or hard-code it as merged.txt).
  2. Ask for the list of source filenames — or accept them as command-line arguments.
  3. Open the destination with fopen("merged.txt", "w"). This creates or truncates the output file.
  4. For each source file: open it in read mode, copy its contents line by line with fgets()/fputs(), then close it.
  5. 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:

Contents of file1.txt: Line 1 from file1
Line 2 from file1
Contents of file2.txt: Line 1 from file2
Line 2 from file2

Running the program:

Console: Enter the output filename: merged.txt
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:

Contents of merged.txt: Line 1 from file1
Line 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.
⚠️ Important: The destination file is opened with "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, fgets returns 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), ensure fclose is still called on any open files. The current version is safe because continue only fires when src is already NULL.
  • 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, fgets returns 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 n is within a reasonable range before allocating or looping — the MAX_FILES guard 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 -g to catch unused variables and format-string mismatches.
  • On Windows, if the source files were created on Unix, fgets in text mode still converts \n correctly — the merge is portable.

📖 Related Tutorials in This Series

  • File Handling Assignments — Complete Index
  • 15. Copy the Contents of One Text File into Another
  • 1. Create a New Text File and Write Text in It
  • 4. Read and Display the Contents of a Text File
  • 14. Append Text to an Existing Text File
  • File Handling in C — Introduction
  • Files FAQ

Previous Problem: -->> 8. Read Binary Data from a Binary File and Display It   ||   Next Problem: -->> 10. Replace a Word with Another Word in a Text File

Back to Index: -->> File Handling Assignments in C


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.