- 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 庫 - fgets() 函式
C 庫函式 fgets(FILE *stream) 從指定的流中讀取下一個字元(無符號字元),並推進流的位置指示器。它通常用於從檔案或標準輸入 (stdin) 讀取輸入。
語法
以下是 C 庫函式 fgets() 的語法:
char *fgets(char *str, int n, FILE *stream);
引數
此函式接受三個引數:
- char *str : 指向字元陣列的指標,讀取的字串將儲存在此陣列中。此陣列應足夠大,以容納字串,包括終止空字元。
- int n: 要讀取的最大字元數,包括終止空字元。fgets 將最多讀取 n-1 個字元,為空字元預留空間。
- FILE *stream: 指向 FILE 物件的指標,指定要從中讀取的輸入流。這可以是從 fopen 等函式獲得的檔案指標,也可以是 stdin(標準輸入)。
返回值
成功時,fgets 返回與傳入相同的指標 str,該指標現在包含已讀取的字串。如果發生錯誤,或者達到檔案結尾且未讀取任何字元,則 fgets 返回 NULL。
示例 1:從標準輸入讀取一行
此示例從標準輸入讀取一行文字並列印它。緩衝區大小為 50,允許最多 49 個字元長的行(加上空終止符)。
以下是 C 庫 fgets() 函式的示例。
#include <stdio.h>
int main() {
char buffer[50];
printf("Enter a string: ");
if (fgets(buffer, sizeof(buffer), stdin) != NULL) {
printf("You entered: %s", buffer);
} else {
printf("Error reading input.");
}
return 0;
}
輸出
以上程式碼產生以下結果:
Enter a string: Welcome to tutorials point You entered: Welcome to tutorials point
示例 2:處理檔案結尾
此示例使用較小的緩衝區大小逐行讀取檔案,顯式處理檔案結尾條件。如果到達檔案結尾,則會列印一條訊息。
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "r");
char buffer[20];
if (file == NULL) {
printf("Failed to open file.\n");
return 1;
}
while (fgets(buffer, sizeof(buffer), file) != NULL) {
printf("Read: %s", buffer);
}
if (feof(file)) {
printf("End of file reached.\n");
} else if (ferror(file)) {
printf("An error occurred.\n");
}
fclose(file);
return 0;
}
輸出
執行以上程式碼後,我們得到以下結果:
(This output will depend on the contents of example.txt) End of file reached.
廣告