The files which are to be merged are opened in "read" mode and the file which contains content of both the files is opened in "write" mode. To merge two files first we open a file and read it character by character and store the read contents in the merged file then we read the contents of another file and store it in merged file, we read two files until EOF (end of file) is reached.
PROGRAM
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
clrscr();
FILE *fs1, *fs2, *ft;
char ch, fname1[20], fname2[20], fname3[30];
printf("Enter first file name (with extension like file1.txt) : ");
gets(fname1);
printf("Enter second file name (with extension like file2.txt) : ");
gets(fname2);
printf("Enter name of file (with extension like file3.txt) which will store the contents of the two files (fname1 and fname1) : ");
gets(fname3);
fs1=fopen(fname1, "r");
fs2=fopen(fname2, "r");
if(fs1==NULL || fs2==NULL)
{
printf("Error Message ");
printf("Press any key to exit...\n");
getch();
exit(EXIT_FAILURE);
}
ft=fopen(fname3, "w");
if(ft==NULL)
{
perror("Error Message ");
printf("Press any key to exit...\n");
getch();
exit(EXIT_FAILURE);
}
while((ch=fgetc(fs1))!=EOF)
{
fputc(ch, ft);
}
while((ch=fgetc(fs2))!=EOF)
{
fputc(ch, ft);
}
printf("The two files were merged into %s file successfully..!!", fname3);
fclose(fs1);
fclose(fs2);
fclose(ft);
getch();
}
No comments:
Post a Comment