Name this program merge. c- The program uses two input files specified on the co
ID: 3922027 • Letter: N
Question
Name this program merge. c- The program uses two input files specified on the command line, via argv[1] and argv [2]. Both files contain unique integer in ascending order. Your program prints the list of integers that exist in either file. The program only prints a given integer once. For example, given the two input files shown below, the program would generate the output in red. The unique numbers are: -812 -407 -99 -55 -22144 99 1831 2015 2016 The basic algorithm to complete this task is shown below: Read the initial number from both files While there are numbers left in both files - neither file has hit end-of-file (EOF) Compare the two numbers If the numbers are the same, print the value once and read the next number from both files Otherwise, print the smaller number and read the next value from that file Your loop exits as soon as you hit end-of-file (EOF) on either file If there are any numbers left in file one (it has not hit EOF), then finish processing that file If there are any numbers left in file two (it has not hit EOF), then finish processing that fileExplanation / Answer
C program merg.c
#include <stdio.h>
int main(int argc, char *argv[] ) // Command line inputs to the program
{
FILE *fpA,*fpB; // file pointers for file A abd B
int A,B,Ra,Rb; // variable decleration
fpA = fopen(argv[1],"r"); // Opening first file for reading
fpB = fopen(argv[2], "r"); // Opening second file for reading
fscanf(fpA,"%d",&A); // frist reading from file A
fscanf(fpB,"%d",&B); // reading from file B
while(!feof(fpA) && !feof(fpB)) // loop til end of file of any file
{
if(A == B) // both are equal means print one
{
printf(" %d",A);
Ra = 1; Rb = 1;
}
else if(A < B) // A is smaller means print A
{
printf(" %d",A);
Ra = 1; Rb = 0;
}
else // else print B
{
printf(" %d",B);
Rb = 1; Ra = 0;
}
if(Ra == 1)fscanf(fpA,"%d",&A); // reading from file A
if(Rb == 1)fscanf(fpB,"%d",&B); // reading from file B
}
// checking and printing the ramining values in the variables while exit of loop
if(A < B)printf(" %d %d",A,B);
if(A > B) printf(" %d %d",B,A);
if(A == B) printf(" %d",A);
// printing the remaining elements in the file A if any
if(!feof(fpA))
{
while(!feof(fpA))
{
fscanf(fpA,"%d",&A);
printf(" %d",A);
}
}
// printing the remaining elements in the file B if any
if(!feof(fpB))
{
while(!feof(fpB))
{
fscanf(fpB,"%d",&B);
printf(" %d",B);
}
}
printf(" ");
return 0;
}
A.txt
-812 -99 1 44 99 1831 2016
B.txt
-407 -55 -22 1 99 1831 2015
OUTPUT: Compailing and running
sh-4.3$ gcc -o main *.c sh-4.3$ ./main A.tex B.tex -812 -407 -99 -55 -22 1 44 99 1831 2015 2016 sh-4.3$
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.