Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

EOF, getc() และ feof() ใน C

EOF (End of File)

getc() คืนค่า EOF เมื่ออ่านจบไฟล์

ตัวอย่าง EOF

ไฟล์ "new.txt": "This is demo! This is demo!"

#include <stdio.h>
int main() {
    FILE *f = fopen("new.txt", "r");
    int c = getc(f);
    while(c != EOF) {
        putchar(c);
        c = getc(f);
    }
    fclose(f);
    getchar();
    return 0;
}

ผลลัพธ์

This is demo! This is demo!

getc()

อ่านตัวอักษรเดี่ยวจาก stream คืนค่า int ถ้าล้มเหลวคืน EOF

ไวยากรณ์: int getc(FILE *stream);

ตัวอย่าง getc()

(โค้ดเหมือนตัวอย่าง EOF)

feof()

ตรวจสอบ end-of-file indicator หลังจาก EOF คืนค่า non-zero ถ้าจบไฟล์แล้ว ไม่เช่นนั้น 0

ไวยากรณ์: int feof(FILE *stream)

ตัวอย่าง feof()

#include <stdio.h>
int main() {
    FILE *f = fopen("new.txt", "r");
    int c = getc(f);
    while(c != EOF) {
        putchar(c);
        c = getc(f);
    }
    if(feof(f))
        printf("\nReached to the end of file.");
    else
        printf("\nFailure.");
    fclose(f);
    getchar();
    return 0;
}

ผลลัพธ์

This is demo! This is demo!
Reached to the end of file.