จุดสิ้นสุดของไฟล์ (EOF) บ่งชี้จุดสิ้นสุดของอินพุต
หลังจากที่เราป้อนข้อความ หากเรากด ctrl+Z ข้อความจะสิ้นสุดลง กล่าวคือ แสดงว่าไฟล์ถึงจุดสิ้นสุดไม่มีอะไรให้อ่าน
อัลกอริทึม
อ้างถึงอัลกอริทึมที่ระบุด้านล่างสำหรับ EOF
Step 1: Open file in write mode. Step 2: Until character reaches end of the file, write each character in filepointer. Step 3: Close file. Step 4: Again open file in read mode. Step 5: Reading the character from file until fp equals to EOF. Step 5: Print character on console. Step 6: Close file.
ตัวอย่าง
ต่อไปนี้เป็นโปรแกรม C สำหรับการสิ้นสุดไฟล์ (EOF) -
#include <stdio.h>
int main(){
char ch;
FILE *fp;
fp=fopen("std1.txt","w"); //open the file in write mode
printf("enter the text then press cntrl Z:\n");
while((ch = getchar())!=EOF) //reading char by char until it equals to EOF{
i.e. when u press ctrlZ the while loop terminates
putc(ch,fp);
}
fclose(fp);
fp=fopen("std1.txt","r");
printf("text on the file:\n");
while ((ch=getc(fp))!=EOF) //reading the character from file until fp equals to EOF{
putchar(ch);
}
fclose(fp);
return 0;
} ผลลัพธ์
เมื่อโปรแกรมข้างต้นทำงาน มันจะให้ผลลัพธ์ดังต่อไปนี้ −
enter the text then press cntrl Z: This is the EOF demonstration example if your text typing is over press cntrlZ ^Z text on the file: This is the EOF demonstration example if your text typing is over press cntrlZ