I created this little program which reads two files with sorted numbers and saves them into a third file. The numbers in "sorted1.txt" are "10 20 30 40 50 60 70" and in "sorted2.txt" - "5 15 25 35 45 55 65 75 85 95 105". When I compile and run the program, though, the last compared numbers are 60 and 65, while they should be 70 and 75. Moreover, in the "sorted3.txt" all the numbers are sorted, but 70 and 105 are missing. Can somebody tell me where the code breaks?
int main() {
FILE *fp;
FILE *fp1;
FILE *fp2;
FILE *fp3;
int num, num1, num2;
fp1 = fopen("sorted1.txt", "r");
fp2 = fopen("sorted2.txt", "r");
fp3 = fopen("sorted3.txt", "w");
if(fp1 == NULL || fp2 == NULL) {
printf("File not present!");
exit(1);
}
fscanf(fp1, "%d", &num1);
fscanf(fp2, "%d", &num2);
while( !feof(fp1) && !feof(fp2) ) {
printf("\nComparing %d and %d", num1, num2);
if(num1 < num2) {
fprintf(fp3, "%d ", num1);
printf("\n%d", num1);
fscanf(fp1, "%d", &num1);
} else {
fprintf(fp3, "%d ", num2);
printf("\n%d", num2);
fscanf(fp2, "%d", &num2);
}
}
if(feof(fp1)) {
fp = fp2;
num = num2;
}
else if(feof(fp2)) {
fp = fp1;
num = num1;
}
while(!feof(fp)) {
fprintf(fp3, "%d ", num);
fscanf(fp, "%d", &num);
}
fclose(fp1);
fclose(fp2);
fclose(fp3);
return 0;
}