Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 11

PROGRAM TO MERGE

TWO FILES
PRSENTED BY :
R.TEENA SREE
ECE-A
22R01A0454
MERGING
Merging two files means the content of any two
files (entered by the user at runtime) gets merged into the third
file in a way that the content of the first source file gets copied to
the target file, and then the content of the second source file gets
appended to the target file.
THINGS TO DO BEFORE THE
PROGRAM

Before going through the program, let's first create three


files , namely:

• micro.txt as the first source file


• project.txt as the second source file
• microproject.txt as the target file
.

• The program will ask for the two names of the file from
where the content is copied and then ask for the third file
name where both the files are concatenated and copied
there. If the third file is not present then the program will
automatically create a file with the entered name
LOGIC TO MERGE TWO FILES
TO THIRD FILE

Step by step descriptive logic to merge two files to third file.


• Open both source files in r (read) and destination file in w (write)
mode.
• We read two files until EOF (end of file) is reached.
• Copy file contents from both source files one by one to destination file.
• Close all files to save and release all resources.
C PROGRAM TO MERGE TWO FILES :
#include <stdio.h>

#include

#include <stdlib.h>

void main()

   FILE *fp1, *fp2, *fp3;

char ch, str1[10], str2[10], str3[10];

clrscr(); 

   printf("Enter the FILE1 name to merge : ");

gets(str1); 

printf("Enter the FILE2 name to merge : ");

   gets(str2);

 printf("Enter the merged file name: ");

   gets(str3);

}
.

   
   fp1 = fopen(str1, "r");
   fp2 = fopen(str2, "r");
  fp3 = fopen(str3, "w"); // Opening in write mode
   if ((fp1 == NULL ) || ( fp2 == NULL) || (fp3 == NULL ))
   {
       printf("Error ");
       exit(1);
   }
 
while ((ch = fgetc(fp1)) != EOF)
.

{
   fputc(ch, fp3);
}
   while ((ch = fgetc(fp2)) != EOF)
{
   fputc(ch, fp3);

  printf(“MERGED SUCCESSFULLY”);
   fclose(fp1);
   fclose(fp2);
   fclose(fp3);
  getch();
}
OUTPUT:

Enter the FILE1 name to merge : micro.txt


Enter the FILE2 name to merge : project.txt
Enter the merged file name: microproject.txt
MERGED SUCCESSFULLY
BEFORE :
micro.txt:
Hello World!
project.txt :
This is RAGULA TEENA SREE !!!!

AFTER :
microproject.txt :
Hello World!
This is RAGULA TEENA SREE !!!!

You might also like