使用文件实现复制命令我的代码是复制垃圾?

时间:2014-08-26 03:34:21

标签: c file

使用文件实现复制命令我的代码是复制垃圾。请帮我修复

   #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);
}

1 个答案:

答案 0 :(得分:4)

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

相当于:

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

因此ch1值为0,具体取决于fgetc(fp)!=EOF)是否为真。你想要的是:

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