欢迎访问我的网站,希望内容对您有用,感兴趣的可以加入免费知识星球。

C语言按行读取文本文件

C/C++ 迷途小书童 5年前 (2019-06-06) 397次浏览 0个评论

环境

  • windows 10 64bit
  • clion

代码实操

准备个测试文本文件 test.txt,内容是

I never saw a Moor
I never saw the Sea
Yet know I how the Heather looks
And what a Billow be.
I never spoke with God
Nor visited in Heaven
Yet certain am I of the spot
As if the Checks were given.

然后是源码部分,按照一行一行来解析文本

#include <stdio.h>

// 每行的最大字节数
#define MAX_LINE 1024

int main() {
    FILE *fp;

    // 数据读取的缓冲区
    char strLine[MAX_LINE];

    // 判断文件是否存在以及可读
    if ((fp = fopen("test.txt", "r")) == NULL)
    {
        printf("Open test.txt Falied!\n");
        return -1;
    }

    // 循环读取每一行,直到文件末尾
    while (!feof(fp))
    {
        // 将fp所指向的文件一行内容读到strLine缓冲区
        fgets(strLine, MAX_LINE, fp);
        printf("%s", strLine);
    }

    // 关闭读文件
    fclose(fp);

    return 0;
}

代码执行结果

C parse txt

参考资料

喜欢 (0)

您必须 登录 才能发表评论!