用 C 語言程式解釋檔案結束 (EOF)


檔案結尾 (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.

示例

以下是檔案結尾 (EOF) 的 C 語言程式 −

#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:
"
);    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:
"
);    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

更新於: 2023 年 9 月 14 日

28K+ 瀏覽次數

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.