用程序解释C语言中的feof()函数
问题
C编译器如何在读取时检测到文件已到达末尾?用程序解释。
解决方案
feof()是C语言的文件处理功能,用于查找文件结尾。
我们用于查找文件结尾的逻辑如下-
fp = fopen ("number.txt", "r"); //打开一个文件
printf ("file content is\n");
for (i=0;i<=100;i++){
n = getw(fp); //读取每个数字并存储在n中
if(feof(fp)) //如果文件指针到达末尾,它将中断{
printf ("reached end of file");
break;
}else{
printf ("%d\t", n);
}
}示例
以下是该feof()功能的C程序-
#include<stdio.h>
int main(){
FILE *fp;
int i,n;
fp = fopen ("number.txt", "w");
for (i=0;i<=100;i= i+10){
putw(i,fp);
}
fclose (fp);
fp = fopen ("number.txt", "r");
printf ("file content is\n");
for (i=0;i<=100;i++){
n = getw(fp);
if(feof(fp)){
printf ("reached end of file");
break;
}else{
printf ("%d\t", n);
}
}
return 0;
}输出结果执行以上程序后,将产生以下结果-
file content is 0102030405060708090100reached end of file