Pages

To Merge Two Files in C

Friday 28 June 2013
This C program adds two files and stores the contents of another file. The files are merged and are for reading the file that contains the contents of the two files, open and opened in a write mode. To merge two files first, to open a file and read character by character and content store to read it in another file, and then we read the content of a file and stores it in a file, you can read until EOF (two files the end of the file), is achieved.

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

int main()
{
   FILE *fs1, *fs2, *ft;
   char ch, file1[20], file2[20], file3[20];

   printf("Enter name of first file\n");
   gets(file1);

   printf("Enter name of second file\n");
   gets(file2);

   printf("Enter name of file which will store contents of two files\n");
   gets(file3);

   fs1 = fopen(file1,"r");
   fs2 = fopen(file2,"r");
   if( fs1 == NULL || fs2 == NULL )
   {
      perror("Error ");
      printf("Press any key to exit...\n");
      getch();
      exit(EXIT_FAILURE);
   }
   ft = fopen(file3,"w");
   if( ft == NULL )
   {
      perror("Error ");
      printf("Press any key to exit...\n");
      exit(EXIT_FAILURE);
   }
   while( ( ch = fgetc(fs1) ) != EOF )
   fputc(ch,ft);
   while( ( ch = fgetc(fs2) ) != EOF )

   fputc(ch,ft);
   printf("Two files were merged into %s file successfully.\n",file3);
   fclose(fs1);
   fclose(fs2);
   fclose(ft);
   return 0;
}

No comments:

Post a Comment