编程语言您现在的位置是:首页 > 博客日志 > 编程语言

C语言之按行读取文件

<a href='mailto:'>微wx笑</a>的头像微wx笑 2022-01-21编程语言2907 4 0关键字:   

C语言要按行读取文件,可以使用 fgets和fscanf,但要注意它们的区别。另外要注意的是一行有多长,要设置的缓存buff多大合适。


nA7无知

原文本文件nA7无知

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
outlook,temperature,humidity,windy,play
sunny,hot,high,FALSE,no
sunny,hot,high,TRUE,no
overcast,hot,high,FALSE,yes
rainy,mild,high,FALSE,yes
rainy,cool,normal,FALSE,yes
rainy,cool,normal,TRUE,no
overcast,cool,normal,TRUE,yes
sunny,mild,high,FALSE,no
sunny,cool,normal,FALSE,yes
rainy,mild,normal,FALSE,yes
sunny,mild,normal,TRUE,yes
overcast,mild,high,TRUE,yes
overcast,hot,normal,FALSE,yes
rainy,mild,high,TRUE,no
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
 
bool ReadCsvFile(char* filePath)
{
    char data[100];
    FILE *fp=fopen(filePath,"r");
    if(!fp)
    {
        printf("can't open file\n");
        return false;
    }
    while(!feof(fp))
    {
        fscanf(fp,"%s",&data);
        printf("%s",data);
        printf("\n");
    }
    printf("\n");
    fclose(fp);
    return true;
}
 
int main()
{
    ReadCsvFile("D:\\MyCppProject\\weather.nominal.csv");
    return 0;
}

读取效果
这里写图片描述nA7无知


nA7无知

注意:本例中使用的是“fscanf”,但是它不如“fgets”,参考:fgets和fscanf区别nA7无知


nA7无知

本文为转载文章,版权归原作者所有,不代表本站立场和观点。

很赞哦! (21) 有话说 (0)

相关文章

文章评论