ปัญหา
คอมไพเลอร์ C ตรวจพบได้อย่างไรว่าไฟล์ถึงจุดสิ้นสุดขณะอ่าน อธิบายด้วยโปรแกรม
วิธีแก้ปัญหา
feof() เป็นฟังก์ชันจัดการไฟล์ในภาษา C ซึ่งใช้ค้นหาจุดสิ้นสุดของไฟล์
ตรรกะที่เราใช้ในการหาจุดสิ้นสุดของไฟล์มีดังนี้ -
fp = fopen ("number.txt", "r"); //open a file
printf ("file content is\n");
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);
}
} ตัวอย่าง
ต่อไปนี้เป็นโปรแกรม C สำหรับฟังก์ชัน feof() -
#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 0 10 20 30 40 50 60 70 80 90 100 reached end of file