Issue
When I look at this code I do not see anything wrong with it but obviously there is.
What it does:
read two files line by line comparing the sorted integers and placing the lesser into the output file and then reading and placing the next smaller integer into the file.
it is a merge sort of two sorted lists containing only numbers.
one number on each line like so:
1
23
45
56
78
It opens the three files correctly but it does not seem to write anything into the output file.
why is this?
( I apologize for my badly structured code. )
#include <stdio.h>
#include <stdlib.h>
int main ( int argc, char **argv) {
FILE *source_file_one;
FILE *source_file_two;
FILE *destination_file;
int source_file_one_input = 0;
int source_file_two_input = 0;
source_file_one = fopen(argv[1], "rb");
source_file_two = fopen(argv[2], "rb");
destination_file = fopen(argv[3], "w");
if(argc != 4)
printf("Useage: mergeSort <source_file_1> <source_file_2> <destination_file>\n");
if(source_file_one == NULL)
printf("Unable to open file one: %s\n", argv[1]);
exit(1);
if(source_file_two == NULL)
printf("Unable to open file two: %s\n", argv[2]);
exit(1);
while(!feof(source_file_one)) {
while(!feof(source_file_two)) {
fscanf(source_file_one, "%d", &source_file_one_input);
fscanf(source_file_two, "%d", &source_file_two_input);
if(source_file_one_input > source_file_two_input) {
fprintf(destination_file, "%d", source_file_two_input);
}
else fprintf(destination_file, "%d", source_file_one_input);
}
}
fclose(source_file_one);
fclose(source_file_two);
fclose(destination_file);
}
Solution
There are serious logical problems with your program, but the reason you aren't getting any output is missing braces. Without the braces your program simply hits the first exit(1)
and quits.
if(argc != 4) {
printf("Useage: mergeSort <source_file_1> <source_file_2> <destination_file>\n");
exit(1);
}
if(source_file_one == NULL) {
printf("Unable to open file one: %s\n", argv[1]);
exit(1);
}
if(source_file_two == NULL) {
printf("Unable to open file two: %s\n", argv[2]);
exit(1);
}
As a hint on fixing the logical problems, you do not need nested loops!
Answered By - ooga Answer Checked By - Mary Flores (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.