Write C Program to Merge Two Files into a Third File

C Program to Merge Two Files into a Third File

A C program that opens two input files and one output file, then copies the contents of the first file followed by the second file into the third file using file I/O functions fopen(), fgetc(), fputc(), and fclose().

Program

#include <stdio.h>
#include <stdlib.h>

int main() {
   FILE *f1, *f2, *f3;
   char ch;

   // Open first source file for reading
   f1 = fopen("file1.txt", "r");
   if (f1 == NULL) {
       printf("Cannot open file1.txt ");
       exit(1);
   }

   // Open second source file for reading
   f2 = fopen("file2.txt", "r");
   if (f2 == NULL) {
       printf("Cannot open file2.txt ");
       fclose(f1);
       exit(1);
   }

   // Open destination file for writing
   f3 = fopen("file3.txt", "w");
   if (f3 == NULL) {
       printf("Cannot open file3.txt ");
       fclose(f1);
       fclose(f2);
       exit(1);
   }

   // Copy contents of file1 into file3
   while ((ch = fgetc(f1)) != EOF)
       fputc(ch, f3);

   // Copy contents of file2 into file3
   while ((ch = fgetc(f2)) != EOF)
       fputc(ch, f3);

   printf("Files merged successfully into file3.txt ");

   // Close all files
   fclose(f1);
   fclose(f2);
   fclose(f3);

   return 0;
}

How It Works?

  1. #include <stdio.h> / <stdlib.h> — stdio.h provides file functions (fopen, fgetc, fputc, fclose); stdlib.hprovides exit().
  2. FILE *f1, *f2, *f3; — Declares three file pointers for the two source files and the destination file.
  3. fopen("file1.txt", "r") — Opens the file in read mode("r"). Returns NULL if the file doesn not exist, which we check and handle.
  4. fopen("file3.txt", "w") — Opens/creates the output file in write mode ("w"). Existing content is overwritten.
  5. while ((ch = fgetc(f1)) != EOF) — Reads characters one at a time from file1 until End-Of-File (EOF) is reached.
  6. fputc(ch, f3); — Writes each character to file3.
  7. The second loop repeats the same copy process for file2, appending its contents after file1 is.
  8. fclose(f1); fclose(f2); fclose(f3); — Always close files to flush buffers and free resources.

Example

file1.txt:

Hello from file one.

file2.txt:

Hello from file two.

file3.txt (after running):

Hello from file one.

Hello from file two.

Compile & Run

gcc merge.c -o merge

./merge

5 Views