Question

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);

}
Was it helpful?

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!

OTHER TIPS

  • First, you have serious logical error with you program. the statement of 'if' is wrong. when the program perform to 'if(source_file_one == NULL)', the next step to perform 'exit(1);'

  • Second, the implementation procedure of 'comparing the sorted integers and placing the lesser into the output file' is wrong.

Suggest: you can read file line by line to two arrays, then you compare two arrays. By doing so, you can make it clear.

Hope that it can help you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top