Error in copying two data files in data 3 in c using command line argument

36 views Asked by At

enter image description here

#include<stdio.h>
#include<stdlib.h>
void mergeFiles(FILE *file1, FILE *file2, FILE *file3)
{
    int num;
    while(fscanf(file1,"%d",&num)!=EOF)
    {
        fprintf(file3,"%d\n",&num);
    }
    while(fscanf(file2,"%d",&num)!=EOF)
    {
        fprintf(file3,"%d",&num);
    }
}
int main(int argc, char *argv[]){
    if(argc!=4) {
        printf("Usage : %s<data1><data2><data>\n",argv[0]);
        return 1;
    }
    FILE *file1=fopen(argv[1],"r");
    FILE *file2=fopen(argv[2],"r");
    FILE *file3=fopen(argv[3],"w");
    if(file1==NULL || file2==NULL || file3==NULL){
        fprintf("Error Opening files\n");
        return 1;
    }
    merge files(file1,file2,file3);
    printf("Merged content written to %s\n",argv[3]);
    fclose(file1);
    fclose(file2);
    fclose(file3);
    return 0;
    
}

What error is in this code?
Error in copying two data files in data 3 in c using command line argument

  1. Open file1.txt and file2.txt in read mode.
  2. Open file3.txt in write mode.
  3. Run a loop to one by one copy characters of file1.txt to file3.txt.
  4. Run a loop to one by one copy characters of file2.txt to file3.txt.
  5. Close all files.
1

There are 1 answers

0
Andpuv On

I think the main problems you encounter are the following:

  1. In the mergeFiles function, you pass the address of the local variable 'num' to fprintf instead of the value it contains after calling fscanf (that requires '&num' because fscanf scan the file, decode the number and store it into the respective variable passed as pointer). fprintf requires the value stored into the variable so change '&num' in 'num' and try again.
  2. In the main function, when you invoke mergeFiles be sure to write 'mergeFiles' and not 'merge files' because the second is not the function name (maybe a typographical error).
  3. The error you get by the compiler is caused by missing file pointer that fprintf needs to know where write, then change that line with 'fprintf(stderr, "error: ...")' for example.