Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

You do not need nor may you use arrays for this program. Write a C program NOT C

ID: 665522 • Letter: Y

Question

You do not need nor may you use arrays for this program. Write a C program NOT C++ 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. Each input file contains a list of integers in ascending order, that is they start small and get bigger as they go. After the program is executed, the output file contains the numbers from the two input files in one longer list, also in ascending order. Your program should define a function with three arguments: one for each of the two input FILE pointers and one for the output FILE pointer. The input files should be named numbers1.txt and numbers2.txt, and the output file should be named output.txt.

Merging the files will work by trying to read one number from each file. If you have two numbers, compare them and put the smaller one in the output file. Then try to get a new number from the file that you read from to output the last number. If at any point you only have a number from one file, because the other file is empty, then you can simply read and output the numbers one at a time until that file is empty.

Some test cases that you may want to consider include the following:

What if one of the files contains no numbers?

What if both of the files contain no numbers?

What happens if one of the files has many more numbers than the other?

There is no screen output for your program.

Explanation / Answer

#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. ");
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(input_1 <= input_2)
{
fprintf(output, "%d ", value1);
i1 = fscanf(input_1, "%d", &value1);
}
else
{
fprintf(output, "%d ", value2);
i2 = fscanf(input_2, "%d", &value2);
}
}
while(i1 == 1)
{
fprintf(output, "%d ", value1);
i1 = fscanf(input_1, "%d", &value1);
}
while(i2 == 1)
{
fprintf(output, "%d ", value2);
i2 = fscanf(input_2, "%d", &value2);
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote