C语言教程
C语言控制语句
C语言函数
C语言数组
C语言指针
C语言字符串
C语言数学函数
C语言结构
C语言文件处理
C预处理器

C 读取文件第一行的程序

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

在本例中,您将学习在 C 编程中打印文件的第一行。
要理解此示例,您应该了解以下C 编程 主题:
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 没有找到,程序会打印错误信息。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4