Sunday, 19 December 2010

Program To merge the contents of two files into a third file

Description:

The program will read the contents of two given files and stores them in the third   given file

Program:

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

void 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);

}


Output:

Enter the name of the file 1 Red1
Enter the name of the file 2 Red2
Enter the name of the file 3 Red3

Two files were merged into the file Red3  successfully


Enter the name of the file 1 file1
Enter the name of the file 2 Red2
Enter the name of the file 3 Red3

Error file1 doesn’t exist



Enter the name of the file 1 Red1
Enter the name of the file 2 file2
Enter the name of the file 3 Red3

Error file2 doesn’t exist


Enter the name of the file 1 Red1
Enter the name of the file 2 Red2
Enter the name of the file 3 file3


Error file3 doesn’t exist



Conclusion : The progam is error free


Files

No comments:

Post a Comment