Computer >> Máy Tính >  >> Lập trình >> lập trình C

Giải thích END OF FILE (EOF) bằng Chương trình C

Phần cuối của Tệp (EOF) cho biết sự kết thúc của đầu vào.

Sau khi chúng tôi nhập văn bản, nếu chúng tôi nhấn ctrl + Z, văn bản sẽ kết thúc, tức là nó cho biết tệp đã đến cuối không có gì để đọc.

Thuật toán

Tham khảo thuật toán đưa ra bên dưới cho 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.

Ví dụ

Sau đây là chương trình C cho End of File (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;
}

Đầu ra

Khi chương trình trên được thực thi, nó tạo ra kết quả sau -

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