C语言从文件中读取第一行的程序

要理解这个示例,您应该了解以下 C 编程 主题


从文件中读取第一行的程序

#include <stdio.h>
#include <stdlib.h> // For exit() function
int main() {
    char c[1000];
    FILE *fptr;
    if ((fptr = fopen("program.txt", "r")) == NULL) {
        printf("Error! File cannot be opened.");
        // Program exits if the file pointer returns NULL.
        exit(1);
    }

    // reads text until newline is encountered
    fscanf(fptr, "%[^\n]", c);
    printf("Data from the file:\n%s", c);
    fclose(fptr);

    return 0;
}

如果文件找到,程序会将文件内容保存到字符串 c 中,直到遇到 `'\n'` 换行符为止。

假设 `program.txt` 文件在当前目录下包含以下文本。

C programming is awesome.
I love C programming.
How are you doing? 

程序的输出将是

Data from the file:
C programming is awesome.

如果找不到 `program.txt` 文件,程序将打印错误消息。

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战