I have a program that splits a large, unsorted, file into two smaller files, sorts the two files, then merges them into "final.txt".
The user is asked to enter a guess as to how many lines exist in the original file. The program works fine except when the user's guess is too small (so small that "file1.txt" contains only 1 or 2 lines of text and "file2.txt" contains the majority). In this case the last line of "file1.txt" is written to "final.txt" twice. Any ideas... I know the problem lies in this function?
Code:
void merge_files(void) {
char temp1[80], temp2[80];
int comparison;
FILE *input1, *input2, *output;
input1=fopen("file1.txt", "r");
input2=fopen("file2.txt", "r");
output=fopen("final.txt", "w");
fgets(temp1, 80, input1);
fgets(temp2, 80, input2);
while (!feof(input1) && !feof(input2)) {
comparison=strcmp(temp1, temp2);
if (comparison<0) {
fprintf(output, "%s", temp1);
fgets(temp1, 80, input1);
} else {
fprintf(output, "%s", temp2);
fgets(temp2, 80, input2);
}
}
while (!feof(input1)) {
fprintf(output, "%s", temp1);
fgets(temp1, 80, input1);
}
while (!feof(input2)) {
fprintf(output, "%s", temp1);
fgets(temp1, 80, input2);
}
fclose(input1);
fclose(input2);
fclose(output);
}
Cheers...