用程序解释 C 语言中的 feof() 函数
问题
C 编译器如何在读取时检测到文件已到末尾?用程序解释一下。
解决方案
feof() 是 C 语言中的一个文件处理函数,用于查找文件的末尾。
我们用来查找文件末尾的逻辑如下 -
fp = fopen ("number.txt", "r"); //open a file
printf ("file content is
");
for (i=0;i<=100;i++){
n = getw(fp); //read each number and store in n
if(feof(fp)) {//if file pointer reach to end it will break
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
");
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 0 10 20 30 40 50 60 70 80 90 100 reached end of file
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP