Hi all this is my first post so forgive me if it's incorrectly posted and let me know what I can improve upon in further posts.
My assignment is to:
Write a program that merges the numbers in two files and writes the results to a third file. The program reads input from two different files and writes the output to a third file. Both files contain integers in ascending order(smallest to largest). After the program is executed, the output file contains the numbers from the two input files in one longer list, also in ascending order.
Question:
I've searched online and I think my function is correct, but I'm confused on how to call output is it "w" for writing or "w+" for reading and writing to the screen to check that the numbers have been merged correctly? Also, how do I display the output file of my function on screen?
PHP Code:
#include <stdio.h>
#include <stdlib.h>
void file_merger(FILE *input_1, FILE *input_2, FILE *output);
int main (int argc, char * argv[])
{
FILE *input_1, *input_2, *output;
input_1 = fopen("numbers1.txt", "r");
input_2 = fopen("numbers2.txt", "r");
output = fopen("output.txt", "w+");
if(input_1 == NULL || input_2 == NULL)
{
fprintf(stderr, "File failed to open.\n");
exit(1);
}
fclose(input_1);
fclose(input_2);
fclose(output);
return 0;
}
void file_merger(FILE *input_1, FILE *input_2, FILE *output)
{
int i1, i2, value1, value2;
i1 = fscanf(input_1, "%d", &value1);
i2 = fscanf(input_2, "%d", &value2);
while(i1 == 1 || i2 == 1)
{
if(value1 <= value2)
{
fprintf(output, "%d\n", value1);
i1 = fscanf(input_1, "%d", &value1);
}
if(value2 <= value1)
{
fprintf(output, "%d\n", value2);
i2 = fscanf(input_2, "%d", &value2);
}
while(i1 == 1)
{
fprintf(output, "%d\n", value1);
i1 = fscanf(input_1, "%d", &value1);
}
while(i2 == 1)
{
fprintf(output, "%d\n", value2);
i2 = fscanf(input_2, "%d", &value2);
}
}
}