C 标准库 - <stdio.h>

C 语言 fgets() 函数用于从文件读取一行字符串(含换行符,长度不超过 n-1)。

原型

char *fgets(char *str, int n, FILE *stream);

读取最多 n-1 个字符,遇到换行或 EOF 停止,并在末尾补 \0。读到文件尾返回 NULL。

示例

#include <stdio.h>

int main() {
    char line[100];
    FILE *fp = fopen("test.txt", "r");
    if (fp == NULL) return 1;

    while (fgets(line, sizeof(line), fp) != NULL)
        printf("%s", line);

    fclose(fp);
    return 0;
}

读取 test.txt 的每一行并打印。

注意事项

fgets 比 gets 安全(有长度限制),是读取用户输入的首选。