Pages

Friday, 9 February 2018

write a program that merges lines alternatively from two files and writes the results to stdout. if one file has less lines than the other, the remaining lines from the larger file should simply be copied.


write a program that merges lines alternatively from two files and writes the results to stdout. if one file has less lines than the other, the remaining lines from the larger file should simply be copied.
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int i = 0, c;
    FILE *file1, *file2;
    if(((file1 = fopen("filename1.txt", "r")) == NULL) || ((file2 = fopen("filename2.txt", "r")) == NULL)) {
        fprintf(stderr, "bad file name\n");
        exit(EXIT_FAILURE);
        }
       
        while(i<2) {
            // taking line from file 1.
            while(((c = getc(file1)) != EOF) &&(c != '.'))
             putc(c, stdout);
           
             if(c == EOF)
             i++;
             else
             putc(c, stdout);
           
            // taking line from file 2.
            while(((c = getc(file2)) != EOF) &&(c != '.'))
             putc(c, stdout);
           
             if(c == EOF)
             i++;
             else
             putc(c, stdout);
            }
    while((c = getc(file1)) != EOF)
        putc(c, stdout);   
       
    while((c = getc(file2)) != EOF)
        putc(c, stdout);   
           
        return 0;
    }