C 庫 - fgetc() 函式



C 庫的 fgetc() 函式從指定的流中獲取下一個字元(一個無符號字元),並推進流的位置指示器。它通常用於從檔案中讀取字元。

語法

以下是 C 庫 fgetc() 函式的語法:

int fgetc(FILE *stream);

引數

stream : 指向 FILE 物件的指標,該物件標識輸入流。此流通常透過使用 fopen 函式開啟檔案來獲取。

返回值

該函式返回從流中讀取的字元,作為轉換為 int 型別的無符號字元。如果遇到檔案結尾或發生錯誤,則該函式返回 EOF,它是一個通常定義為 -1 的宏。為了區分實際字元和 EOF 返回值,應該使用 feof 或 ferror 函式來檢查是否已到達檔案結尾或發生錯誤。

示例 1

此示例讀取並列印“example1.txt”的第一個字元。如果檔案為空或發生錯誤。

#include <stdio.h>

int main() {
   FILE *file = fopen("example1.txt", "r");
   if (file == NULL) {
      perror("Error opening file");
      return 1;
   }

   int ch = fgetc(file);
   if (ch != EOF) {
      printf("The first character is: %c\n", ch);
   } else {
      printf("No characters to read or error reading file\n");
   }
   fclose(file);
   return 0;
}

輸出

以上程式碼產生以下結果:

The first character is: H

示例 2:統計檔案中的字元數

此示例統計並列印“example3.txt”中的字元總數。

#include <stdio.h>

int main() {
   FILE *file = fopen("example3.txt", "r");
   if (file == NULL) {
      perror("Error opening file");
      return 1;
   }

   int ch;
   int count = 0;
   while ((ch = fgetc(file)) != EOF) {
      count++;
   }

   printf("Total number of characters: %d\n", count);

   fclose(file);
   return 0;
}

輸出

執行上述程式碼後,我們得到以下結果:

Total number of characters: 57
廣告