0

Implementing copy command using file my code is copying garbage.please help me to fix

   #include<stdio.h>
    int main()
{
    char ch;
    FILE *fp,*fp1;
    fp=fopen("source","r");
    if(fp==NULL)
    {
            printf("no file\n");
            return;
    }
    else
    {
            printf("file is present\n");
            fp1=fopen("dest","w");
            while(ch=fgetc(fp)!=EOF)
            fputc(ch,fp1); // why source contain is not copyed to dest?
    }
             fclose(fp);
             fclose(fp1);
}
  • Hint: http://en.cppreference.com/w/c/language/operator_precedence – Adam Rosenfield Aug 26 '14 at 03:36
  • You might want to read about [operator precedence](http://en.cppreference.com/w/c/language/operator_precedence), and then look again at your loop condition. – Some programmer dude Aug 26 '14 at 03:37
  • 2
    Also, the return type of `fgetc` is `int`. You should change `char ch;` to `int ch;`. – R Sahu Aug 26 '14 at 03:42
  • @RSahu upon success it return chararcter after converting it to an int without sign extension.Upon failure or end of file or error it return EOF ie -1 – carrer carrer Aug 26 '14 at 03:59
  • @carrercarrer, if you are not convinced that `int ch;` is the right thing to do, please checkout http://stackoverflow.com/a/23331786/434551. – R Sahu Aug 26 '14 at 04:02

1 Answers1

4
while(ch=fgetc(fp)!=EOF)

is eqivalent to:

while(ch = (fgetc(fp)!=EOF))

thus gives ch values either 1 or 0 depending on whether fgetc(fp)!=EOF) is true. What you want is:

while((ch = fgetc(fp)) != EOF)
Yu Hao
  • 119,891
  • 44
  • 235
  • 294