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