Wednesday, November 11, 2009

Chap12[C]f Merge alternate lines from two files

Write a program that merges lines alternately from two files and writes the results to new file. If one file has less number of lines than the other, the remaining lines from the larger file should be simply copied into the target file.

#include "stdio.h"
void main()
{
FILE *fp,*ft,*fs;
char ch;
int f1=1,f2=1,counter=1;

fp=fopen("c:\\ctxt\\first.txt","r");
ft=fopen("c:\\ctxt\\second.txt","r");
fs=fopen("c:\\ctxt\\combine.txt","w");

while(1)
{
if(counter==1||f2==0)
{
ch=fgetc(fp);
if(ch==EOF)
f1=0;
if(ch=='\n'||ch==46)
counter=2;
if(f1!=0)
fputc(ch,fs);
}

if(counter==2||f1==0)
{
ch=fgetc(ft);
if(ch==EOF)
f2=0;

if(ch=='\n'||ch==46)
counter=1;
if(f2!=0)
fputc(ch,fs);

if(f1==0&&f2==0)
break;
}
}

fclose(fp);
fclose(ft);
fclose(fs);
}

2 comments:

  1. I have a dout according to question both the line of different file comes in one line but when i run this it shows in different line

    ReplyDelete