C

C Program To Merge Two Files Into a Single File

In this tutorial, we are going to see how to write a C program to merge two files into a single file and store their contents in another file. The files to be merged are opened in “read” mode and the file containing the two files is opened in “write” mode.
 

C Program To Merge Two Files Into a Single File
#include <stdio.h> 
#include <stdlib.h>
  
int main() 
{ 
   // Open the two files to be merged
   FILE *f1 = fopen("file1.txt", "r"); 
   FILE *f2 = fopen("file2.txt", "r"); 
  
   // Open file to store the result
   FILE *f3 = fopen("file3.txt", "w"); 
   char c; 
  
   if (f1 == NULL || f2 == NULL || f3 == NULL) 
   { 
         puts("Cannot open files"); 
         exit(EXIT_FAILURE);
   } 
  
   // Copy the content of the first file to file3.txt
   while ((c = fgetc(f1)) != EOF) 
      fputc(c, f3); 
  
   // Copy the content of the second file to file3.txt
   while ((c = fgetc(f2)) != EOF) 
      fputc(c, f3); 
  
   printf("The two files are now merged in file3.txt"); 
  
   fclose(f1); 
   fclose(f2); 
   fclose(f3); 
   return 0; 
}

Output:

The two files are now merged in file3.txt

 

mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *