关于feof函数的一点问题
2006-03-30 12:39
309 查看
#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);
}
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);
}
相关文章推荐
- 关于 while(1)和for(;;)效率问题的一点想法
- Java中关于String的一点小问题!
- 关于跨域问题和安全性的一点理解
- 关于ClassLoader的一点小问题
- 关于乱码的一点问题
- 关于使用“远程桌面连接”中碰到的一点问题!
- 关于VC数据库开发中数据库连接与效率的问题-----一点体会和经验
- 输入输出时关于缓冲区的一点问题
- 关于字符的一点问题
- 关于NHibernate的更新和读取操作,及碰见的一点问题
- [C#]关于DLL使用.exe.config 的问题,也许以下描述有一点帮助
- [C#]关于DLL使用.exe.config 的问题,也许以下描述有一点帮助
- 关于修改frameworks的源码遇到的一点问题以及解决方法
- 关于c#里面DataGridView的一点问题
- 关于Android5.x适配的一点小问题(NDK error: SIGABRT)
- 关于OpenERP客户端字体问题的一点心得
- 关于文件读取的一点小问题
- 一点关于复制构造函数的问题
- linux环境下调试嵌入式设备时出现Aborted、segmentation fault、卡死的问题以及关于指针使用的一点想法
- 关于Access数据库的一点小问题