环境
- 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;
}
代码执行结果