0

The program takes command line arguments for source and destination file.

#include<stdio.h>
void main(int argc,char *argv[])
{
  if(argc!=3)
  {
    printf("Very few arguments to operate on");
    return;
  }
    FILE *sp,*dp;
    char c;
    sp=fopen(argv[1],"r");
    if(sp==NULL)
    {
      printf("%s cannot be opened in read only mode. make sure the file exists",argv[1]);
      return;
    }
    dp=fopen(argv[2],"w+");
    if(dp==NULL)
    {
      printf("%s cannot be created",argv[2]);
      return;
    }
    while(!feof(sp))
    {
      c=fgetc(sp);
      fputc(c,dp);
    }
    fclose(sp);
    fseek( dp, 0, SEEK_SET );
    while(!feof(dp)){
      c=fgetc(dp);
      printf("%c",c);
    }
    fclose(dp);
}

but if the source file has "Hi! I an Anudeep" then after copying the file has "Hi! I an Anudeepÿ". Help me fix this.

Stargateur
  • 24,473
  • 8
  • 65
  • 91
  • 4
    That's because you're writing an EOF to the destination file. – user253751 Nov 24 '17 at 01:30
  • 1
    Please read [this](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong). BTW `char c` -> `int c` – Ed Heal Nov 24 '17 at 01:32
  • 3
    `c` needs to be `int` not `char`. You don't want to loop `while (! feof(sp))` (because by the time `feof()` is set you have already read one character too many) but rather `while ((c = fgetc(sp)) != EOF)`. – AlexP Nov 24 '17 at 01:37

0 Answers0