C Program to merge contents of two files into a third file Read Discuss Courses Practice Improve Improve Improve Like Article Like Save Article Save Report issue Report Let the given two files be file1.txt and file2.txt. The following are steps to merge. 1) Open file1.txt and file2.txt in read mode. 2) Open file3.txt in write mode. 3) Run a loop to one by one copy characters of file1.txt to file3.txt. 4) Run a loop to one by one copy characters of file2.txt to file3.txt. 5) Close all files. To successfully run the below program file1.txt and fil2.txt must exits in same folder. #include <stdio.h> #include <stdlib.h> int main() { // Open two files to be merged FILE *fp1 = fopen("file1.txt", "r"); FILE *fp2 = fopen("file2.txt", "r"); // Open file to store the result FILE *fp3 = fopen("file3.txt", "w"); char c; if (fp1 == NULL || fp2 == NULL || fp3 == NULL) { puts("Could not open files"); exit(0); } // Copy contents of first file to file3.txt while ((c = fgetc(fp1)) != EOF) fputc(c, fp3); // Copy contents of second file to file3.txt while ((c = fgetc(fp2)) != EOF) fputc(c, fp3); printf("Merged file1.txt and file2.txt into file3.txt"); fclose(fp1); fclose(fp2); fclose(fp3); return 0; } Output: Merged file1.txt and file2.txt into file3.txt Related Articles : Java program to merge two files alternatively into third file Java program to merge two files into a third file Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now! Last Updated : 07 Jul, 2017 Like Article Save Article Previous C program to delete a file Next What is the difference between printf, sprintf and fprintf? Please Login to comment...