
- C 標準庫
- C 庫 - 首頁
- C 庫 - <assert.h>
- C 庫 - <complex.h>
- C 庫 - <ctype.h>
- C 庫 - <errno.h>
- C 庫 - <fenv.h>
- C 庫 - <float.h>
- C 庫 - <inttypes.h>
- C 庫 - <iso646.h>
- C 庫 - <limits.h>
- C 庫 - <locale.h>
- C 庫 - <math.h>
- C 庫 - <setjmp.h>
- C 庫 - <signal.h>
- C 庫 - <stdalign.h>
- C 庫 - <stdarg.h>
- C 庫 - <stdbool.h>
- C 庫 - <stddef.h>
- C 庫 - <stdio.h>
- C 庫 - <stdlib.h>
- C 庫 - <string.h>
- C 庫 - <tgmath.h>
- C 庫 - <time.h>
- C 庫 - <wctype.h>
- C 標準庫資源
- C 庫 - 快速指南
- C 庫 - 有用資源
- C 庫 - 討論
- C 程式設計資源
- C 程式設計 - 教程
- C - 有用資源
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
廣告