C 語言中的 EOF、getc() 和 feof()


EOF

EOF 代表 檔案結束。函式 getc() 在成功時返回 EOF。

以下是在 C 語言 中使用 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!

在上述程式中,檔案是使用 fopen() 開啟的。當整數變數 c 不等於 EOF 時,它將讀取檔案。

FILE *f = fopen("new.txt", "r");
int c = getc(f);
while (c != EOF) {
   putchar(c);
   c = getc(f);
}

getc()

它從輸入中讀取單個字元並返回一個整數值。如果失敗,則返回 EOF。

以下是 C 語言中 getc() 的語法:

int getc(FILE *stream);

以下是 C 語言中 getc() 的示例:

假設我們有一個名為 "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!

在上述程式中,檔案是使用 fopen() 開啟的。當整數變數 c 不等於 EOF 時,它將讀取檔案。函式 getc() 正在從檔案中讀取字元。

FILE *f = fopen("new.txt", "r");
int c = getc(f);
while (c != EOF) {
   putchar(c);
   c = getc(f);
}

feof()

函式 feof() 用於在 EOF 後檢查檔案結束。它測試檔案結束指示符。如果成功,則返回非零值,否則返回零。

以下是 C 語言中 feof() 的語法:

int feof(FILE *stream)

以下是 C 語言中 feof() 的示例:

假設我們有一個名為 "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);
   }
   if (feof(f))
   printf("
Reached to the end of file."
);    else    printf("
Failure."
);    fclose(f);    getchar();    return 0; }

輸出

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

在上述程式中,檔案是使用 fopen() 開啟的。當整數變數 c 不等於 EOF 時,它將讀取檔案。函式 feof() 再次檢查指標是否已到達檔案末尾。

FILE *f = fopen("new.txt", "r");
int c = getc(f);
while (c != EOF) {
   putchar(c);
   c = getc(f);
}
if (feof(f))
printf("
Reached to the end of file."); else printf("
Failure.");

更新時間: 2023年9月14日

25K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告