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

C programming only please. This program takes the names of two input files from

ID: 3675572 • Letter: C

Question

C programming only please.

This program takes the names of two input files from the command line and merges these two files into a single (new) file. Each of these files contains integers, and both input files are in ascending (sorted) order. You should create a new output file named allData that contains all the numbers in the two input files and is in sorted (ascending) order. The example below shows what allData would contain if you had the two data files data1 and data2 as input and ran the program with ./a.out data1 data2.

Example:

data1: 1 5 9 15 82

data2: 2 4 15 18 37 64 99

allData: 1 2 4 5 9 15 18 37 64 82 99

Explanation / Answer

//Program

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
   /* argc should be equal to 2*/
   if ( argc != 3 )
{
printf(" Number of arguments should be equal to 3");
}
FILE *fp1, *fp2, *fp3;

fp1 = fopen(argv[1],"r");
fp2 = fopen(argv[2],"r");

if( fp1 == NULL || fp2 == NULL )
{
printf(" Unable to be open Input file ... ");
exit(0);
}

fp3 = fopen(argv[3],"w");

if( fp3 == NULL )
{
printf(" Unable to be open Output file ... ");
exit(0);
}
int a,b;
fscanf(fp1,"%d",&a);
fscanf(fp2,"%d",&b);
while (!feof(fp1) && !feof(fp2))
{
if (a <= b)
{
fprintf(fp3,"%d ",a);
fscanf(fp1,"%d",&a);
}
else
{
fprintf(fp3,"%d ",b);
fscanf(fp2,"%d",&b);
}
}

while (!feof(fp1))
{
fscanf(fp1,"%d",&a);
       fprintf(fp3,"%d ",a);   
}

while (!feof(fp2))
{
fscanf(fp2,"%d",&b);
       fprintf(fp3,"%d ",b);
}

printf(" Two files were merged into %s file successfully. ",argv[3]);

fclose(fp1);
fclose(fp2);
fclose(fp3);

return 0;
}