Skip to content

Latest commit

 

History

History
56 lines (40 loc) · 1.38 KB

File metadata and controls

56 lines (40 loc) · 1.38 KB

C 程序:从文件中读取一行并显示它

原文: https://www.programiz.com/c-programming/examples/read-file

在此示例中,您将学习从文件中读取文本并将其存储在字符串中,直到遇到换行符'\ n'。

要理解此示例,您应该了解以下 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! opening file");
        // Program exits if 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,则此程序将显示错误消息。