0

For example if the input file contains "my name is ." the content copied in the output file will be "my name is .." Also wanted to ask if the input and output files does not exist will "fopen" create them in the specified location.

MY CODE:

#include<stdio.h>
void copy(FILE *,FILE *);
int main()
{
FILE *input = fopen("/Users/vasuparbhakar/Documents/C Programs/File Handling/copy file/input.txt","r");
FILE *output= fopen("/Users/vasuparbhakar/Documents/C Programs/File Handling/copy file/output.txt","w");
if(input == NULL)
{
    fprintf(stderr,"Error opening file: input.txt");
    return 0;
}
if(output == NULL)
{
    fprintf(stderr,"Error opening file: output.txt");
    return 0;
}

copy(input,output);

fclose(input);
fclose(output);

return 0;
}

void copy(FILE *from,FILE *to)
{                                                           
    char x;

    while(!feof(from))
    {
        fscanf(from,"%c",&x);
        fprintf(to,"%c",x);
    }
}
  • Always check the return value of `fscanf` before using the values (you think) it parsed. – dxiv Jan 22 '21 at 04:24

1 Answers1

0

In your copy loop, feof returns true only after you try to read the file after reading the last character. Since you check only the beginning of your loop, you continue to write to the second file even after fscanf fails. Thus, you write an extra character. To fix, you can either check the return value of fscanf or feof before writing.

As for your question about creating files, you can either look up the manual for fopen using man fopen or look up any of the reference for the standard library online by searching for fopen reference (there are online manual pages too). There you will find an explanation for the modes of the file.

Eg;

r      Open  text  file  for reading.  The stream is positioned at the beginning of the file.

Taken from https://linux.die.net/man/3/fopen . This doesn't mention creating the file so it means it won't create if it doesn't exist.