C Programming
Computer Programming

C file handling program that Merges Lines Alternatively from 2 Files and Print Result



Write C file handling program that Merges Lines Alternatively from 2 Files and Print Result

\* C file handling program that Merges Lines Alternatively from 2 Files and Print Result *\

# include < stdio.h >
int   main( )
{

char file1[10], file2[10], ch ;

/*getting the names of file to be concatenated*/
printf("\n Enter the name of first File : ") ;
scanf("%s", file1) ;
printf(" Enter the name of second File : ") ;
scanf("%s", file2) ;
FILE *fptr1, *fptr2, *fptr3 ;

/*opening the files in read only mode*/
fptr1=fopen(file1, "r") ;
fptr2=fopen(file2, "r") ;

/*opening a new file in write,update mode*/
fptr3=fopen("mergefinal.txt", "w+") ;
char str1[200] ;
char ch1, ch2 ;
int n = 0, w = 0;
while (((ch1=fgetc(fptr1)) != EOF) && ((ch2 = fgetc(fptr2)) != EOF))
{

      /*getting lines in alternately from two files*/
      if (ch1 != EOF)
      {
            ungetc(ch1, fptr1) ;
            fgets(str1, 199, fptr1) ;
            fputs(str1, fptr3) ;
            if (str1[0] != 'n')
                  n++ ;
      }
      if (ch2 != EOF)
      {
            ungetc(ch2, fptr2) ;
            fgets(str1, 199, fptr2 ) ;
            fputs(str1, fptr3 ) ;
            if (str1[0] != 'n')
            n++ ;
      }
}

rewind( fptr3 ) ;
while ((ch1 = fgetc(fptr3)) != EOF)
{
      /*countig no.of words*/
      ungetc(ch1, fptr3) ;
      fscanf(fptr3, "%s", str1) ;
      if (str1[0] != ' ' || str1[0] != 'n')
            w++ ;
}

fprintf(fptr3, "\n\n Number of lines = %d n Number of words is = %d\n", n, w - 1) ;

/*appendig comments in the concatenated file*/
printf("\n Content in the final file are.\n\n");

fclose(fptr1) ;
fclose(fptr2) ;
fclose(fptr3) ;

fptr3 = fopen("mergefinal.txt", "r") ;
ch = fgetc(fptr3) ;
while (ch != EOF)
{
      printf ("%c", ch) ;
      ch = fgetc(fptr3) ;
}
fclose(fptr3) ;
return 0;

}

Output of Program :

Output of C file handling program that Merges Lines Alternatively from 2 Files and Print Result