codescracker


c

C Program to Merge Two Files



« Previous Program Next Program »


Merge Two Files in C

To merge two files in C programming, first open the two file and start copying the content of the first file to the third file(target file) after this start appending the content of the second file to the third file (target file)

C Programming Code to Merge Two Files

Following C program merge two files and store the content of both the file into another file. So the following C program ask to the user to enter the three file names. First file name and second file name (say file1.txt and file2.txt), then third file name that is used to store the content of the two file (say filet.txt). So the following C program merge the two file and write it into the third file :

/* C Program - Merge Two Files */
		
#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)
	{
		perror("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();
}

When the above c program is compile and executed, it will produce the following result:

c program to merge two files

Same Program in Other Programming Language

You may also like same program in other programming languages:


« Previous Program Next Program »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test