0

I am trying to copy contents of one file to another character by character using a loop.

    #include <stdio.h>
    #include <stdlib.h>
    int main(){
    
    FILE * fp1=fopen("file1.txt","r");
    FILE * fp2=fopen("file2.txt","w");
    
    char c;
    while(!feof(fp1)){
       c=fgetc(fp1);
       fputc(c,fp2);
       }
   return 0;
  }

Consider that we have hello in the file1, after running the code the content present in file2 is hello�.

Why I am getting this extra character ()? Is there anything wrong with my piece of code?

Gerhardh
  • 11,688
  • 4
  • 17
  • 39
Sai
  • 71
  • 7

1 Answers1

1

feof returns non-zero value after fgetc returns EOF. Therefore, the program has fputc the EOF returned by fgetc.

You can do the following.

int c;
while ((c = fgetc(fp1)) != EOF) {
    fputc(c, fp2);
}

Use int instead of char for c to be able to determine the value EOF.

  • fgetc returns EOF even when an error occurs . feof returns non zero value only when end of file is reached but it works concurrently. Which is better one to use ?? – Sai May 14 '22 at 14:49
  • You can use ferror() or feof() after the loop. https://stackoverflow.com/questions/4292729/fgetc-is-it-enough-to-just-check-eof – Itagaki Fumihiko May 14 '22 at 15:15