I want to merge two files in C, and stop in the end.
I have a program but it keeps spelling out words even after my file is ended. For example:
File 1:
a
b
c
File 2:
1
2
3
4
5
And the result I get is:
a
1
b
2
c
3
c
4
c
5
And I want:
a
1
b
2
c
3
4
5
I think it's my if
statement in my while
loop that is my issue.
I don't know how to define that.
My code is:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char d[200]; //char för da.txt
char h[200]; //char för hej.txt
FILE *hptr, *dptr;
hptr = fopen("hej.txt", "r"); //Öppna hej.txt => hptr
dptr= fopen("da.txt", "r"); //Öppna da.txt => dptr
/*
if(((hptr) == NULL && (dptr) == NULL)) //Fall 1
{
printf("Error, båda filerna är tom");
exit(1);
}
if ((hptr) == NULL) //Fall 2 när hej.txt är tom
{
fscanf(dptr,"%[^/]", d); //Hämtar från da.txt
printf("\nFil 2:\n%s", d); //Skriver ut från da.txt
exit(1);
}
if ((dptr) == NULL) //Fall 3 när da.txt är tom
{
fscanf(hptr,"%[^/]", h); //Hämtar från hej.txt
printf("Fil 1:\n%s", h); //Skriver ut från hej.txt
exit (1);
} */
if(hptr != NULL || dptr != NULL) //Fall 4 när ingen fil är tom
{
while (!feof (hptr) && !feof (dptr))
{
if (hptr ***I guess this is the problem*** == feof)
{
fgets(d, 200, dptr);
printf("%s", d);
}
if (hptr == feof)
{
fgets(h, 200, hptr);
printf("%s", h);
}
}
fclose (hptr);
fclose (dptr);
}
//getch();
return EXIT_SUCCESS;
}