Program to merge two files in C.

#include<stdio.h>
main()
{
char f1[10],f2[10];
puts("enter the name of file 1");      /*getting the names of file to be concatenated*/
scanf("%s",f1);
puts("enter the name of file 2");
scanf("%s",f2);
FILE *fa,*fb,*fc;
fa=fopen(f1,"r");             /*opening the files in read only mode*/
fb=fopen(f2,"r");
fc=fopen("merge.txt","w+");   /*opening a new file in write,update mode*/
char str1[200];
char ch1,ch2;
int n=0,w=0;
while( (( ch1=fgetc(fa) )!=EOF)&&((ch2=fgetc(fb))!=EOF))
{
if(ch1!=EOF)             /*getting lines in alternately from two files*/
{ ungetc(ch1,fa);
fgets(str1,199,fa);
fputs(str1,fc);
if(str1[0]!='\n') n++;      /*counting no. of lines*/
}
if(ch2!=EOF)
{ ungetc(ch2,fb);
fgets(str1,199,fb);
fputs(str1,fc);
if(str1[0]!='\n')n++;        /*counting no.of lines*/
}
}
rewind(fc);
while((ch1=fgetc(fc))!=EOF)       /*countig no.of words*/
{
ungetc(ch1,fc);
fscanf(fc,"%s",str1);
if(str1[0]!=' '||str1[0]!='\n')
w++;
}
fprintf(fc,"\n\n number of lines = %d \n number of words is = %d\n",n,w-1);
/*appendig comments in the concatenated file*/
fclose(fa);
fclose(fb);
fclose(fc);
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s