0

Hi I have trying to merge two text files alternatively in a way that I get one line from first file and then I get second line from the next one, please help me, spent way too much time on this and still cannot get anything on the new file. Code is given below.

#include<stdio.h>
#include<stdlib.h>

int main()
{
    FILE *pointer1, *pointer2, *pointer3;
    char source1[80],source2[80],target[80];
    char ch1,ch2;

    printf("Enter the source and source 2\n");
    scanf("%s %s", source1,source2);

    printf("Enter the destination\n");
    scanf("%s",target);

    pointer1 = fopen(source1,"r");
    pointer2 = fopen(source2,"r");
    pointer3 = fopen(target,"w");

    if(pointer1 == NULL || pointer2==NULL || pointer3==NULL)
    {
        printf("Cannot open a file\n ");
        exit(1);
    }
    

    while(1)
    {
        if(ch1!=EOF)
        {
            ch1 = fgetc(pointer1);
            while(ch1!='\n')
            {
                if(ch1==EOF)
                    break;
                fputc(ch1,pointer3);
                ch1=fgetc(pointer1);
            }
        }
        if(ch2!=EOF)
        {
            ch2=fgetc(pointer2);
            while(ch2!='\n')
            {
                if(ch2==EOF)
                    break;
                fputc(ch2,pointer3);
                ch2=fgetc(pointer2);
            }
        }

        if(ch1==EOF && ch2==EOF)
            break;
    }

    printf("Merging completed successfully\n");
    printf("Press any key to exit\n");
    getch();
}
  • first problem, you check `if(ch1!=EOF)` when `ch1` has an indeterminant value. Same with `ch2`. – yano Oct 27 '21 at 18:48
  • 1
    You can read character by character and check for newlines yourself, but I strongly recommend using [`fgets`](https://linux.die.net/man/3/fgets) to read line-by-line. That's its whole purpose. – yano Oct 27 '21 at 18:50
  • also note that [`fgetc`](https://man7.org/linux/man-pages/man3/fgetc.3.html) returns an `int`, not a `char` – yano Oct 27 '21 at 18:54
  • Never mind guys got it solved, did not close the file pointer, stupid me!!! – Ashish Bajpai Oct 27 '21 at 18:55
  • [buffers should flush and open file pointers should close](https://stackoverflow.com/questions/8175827/what-happens-if-i-dont-call-fclose-in-a-c-program) if your process exits gracefully .. ? – yano Oct 27 '21 at 19:00

0 Answers0