关于feof函数的一点问题

#include <stdio.h>

int main()
{
    FILE *in,*out;
    char ch,infile[10],outfile[10];

    printf("Enter the infile name:");
    scanf("%s",infile);
    in=fopen(infile,"r");
   
    if(in==NULL)
    {
        printf("Can't open the file that you want read!");
        return 1;
    }

    printf("Enter the outfile name:");
    scanf("%s",outfile);
    out=fopen(outfile,"w");
    if(out==NULL)
    {
        printf("Can't open the file that you want to write!");
        return 1;
    }

    while(!feof(in))
    {
        ch=fgetc(in);
        putchar(ch);
        fputc(ch,out);
    }
 
    fclose(in);
    fclose(out);
   
    return 0;
}

上面这个小程序,每次运行后,目标文件会比源文件多一个字节,比如,源文件Test1.txt的内容是:
hehe
运行后,目标文件Test2.txt的内容却是:
hehe
用记事本打开看的,多了一个字节,变成了5字节

上面这段程序在谭浩强的C程序设计(第二版)中也有这个问题,这实际上是对feof这个函数的处理方式不理解所造成的,实际上:

当feof(FILE *)读到EOF标志并不认为文件结束了,依旧返回0,直到读到EOF的下一个字符才返回1,这时才认为是文件结束。

因此若以while(!feof(fp))为循环条件的时候,要将一个文件(fp)完全复制到另一个文件(fp1),需要加上判断if(ch!=-1),如下:


while(!feof(in))
 {
  ch=fgetc(in);
  if(ch!=-1)
  fputc(ch,out);

  }

或者:

 while(true)
    {
        ch=fgetc(in);
        if(feof(in))
         break;
        putchar(ch);
        fputc(ch,out);
    }

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值