ฟังก์ชัน feof() คืออะไร?
feof() เป็นฟังก์ชันจัดการไฟล์ (File Handling) ในภาษา C ใช้ตรวจสอบว่า **อ่านถึงปลายไฟล์ (End of File) แล้วหรือยัง**
ตรรกะการใช้งาน
FILE *fp = fopen("number.txt", "r"); // เปิดไฟล์อ่าน
printf("File content:\n");
for (int i = 0; i <= 100; i++) {
int n = getw(fp); // อ่านตัวเลขแต่ละตัว
if (feof(fp)) { // ถ้าถึงปลายไฟล์
printf("Reached end of file");
break;
} else {
printf("%d\t", n);
}
}
ตัวอย่างโปรแกรมสมบูรณ์
#include <stdio.h>
int main() {
FILE *fp;
int i, n;
// เขียนข้อมูลลงไฟล์ก่อน (เตรียมข้อมูลทดสอบ)
fp = fopen("number.txt", "w");
for (i = 0; i <= 100; i += 10)
putw(i, fp);
fclose(fp);
// อ่านข้อมูลและตรวจสอบ feof()
fp = fopen("number.txt", "r");
printf("File content:\n");
for (i = 0; i <= 100; i++) {
n = getw(fp);
if (feof(fp)) {
printf("\nReached end of file");
break;
} else {
printf("%d\t", n);
}
}
fclose(fp);
return 0;
}
ผลลัพธ์:
File content:
0 10 20 30 40 50 60 70 80 90 100
Reached end of file
ข้อควรระวัง (Important Notes)
feof()จะคืนค่า true (non-zero) ก็ต่อเมื่อ **พยายามอ่านเกินปลายไฟล์แล้ว** ไม่ใช่ตอนชี้อยู่ที่ตัวสุดท้าย- รูปแบบที่แนะนำ: ใช้
while ((ch = fgetc(fp)) != EOF)แทนการใช้ feof() ใน loop condition - ต้อง
#include <stdio.h>
รูปแบบที่แนะนำ (Best Practice)
int ch;
while ((ch = fgetc(fp)) != EOF) {
// ประมวลผล ch
}
วิธีนี้ปลอดภัยกว่าและเป็นมาตรฐานมากกว่า