Vấn đề
Trình biên dịch C phát hiện hết file như thế nào khi đọc? Giải thích kèm chương trình.
Giải pháp
feof() là hàm xử lý file trong C, dùng để kiểm tra đã đạt cuối file hay chưa.
Logic kiểm tra cuối file:
fp = fopen ("number.txt", "r"); // mở file printf ("file content is\n"); for (i=0;i<=100;i++){ n = getw(fp); // đọc số, lưu vào n if(feof(fp)) { // nếu con trỏ file đạt cuối printf ("reached end of file"); break; } else { printf ("%d\t", n); } }
Ví dụ
Chương trình C minh họa 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; }
Kết quả
file content is 0 10 20 30 40 50 60 70 80 90 100 reached end of file