用程式解釋 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