- 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 库 - 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.
广告