libcsv库解析csv文件

2020-11-07  本文已影响0人  一路向后

1.程序源码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <csv.h>

struct counts {
        unsigned long fields;
        unsigned long rows;
        char buf[1024];
};

//列回调函数
void cb1(void *s, size_t len, void *data)
{
        ((struct counts *)data)->fields++;
        strcat(((struct counts *)data)->buf, s);
        strcat(((struct counts *)data)->buf, "; ");
}

//行回调函数
void cb2(int c, void *data)
{
        printf("%s\n", ((struct counts *)data)->buf);
        ((struct counts *)data)->rows++;
        memset(((struct counts *)data)->buf, 0x00, 1024);
}

int main()
{
        FILE *fp;
        struct csv_parser p;
        char buf[1024];
        size_t bytes_read;
        struct counts c = {0,0};

        memset(&c, 0x00, sizeof(c));

        //初始化解析器
        if(csv_init(&p, 0) != 0)
        {
                exit(EXIT_FAILURE);
        }

        //打开文件
        fp = fopen("1.csv", "rb");
        if(fp == NULL)
        {
                exit(EXIT_FAILURE);
        }

        while((bytes_read=fread(buf, 1, 1024, fp)) > 0)
        {
                //解析csv文件
                if(csv_parse(&p, buf, bytes_read, cb1, cb2, &c) != bytes_read)
                {
                        fprintf(stderr, "Error while parsing file: %s\n", csv_strerror(csv_error(&p)));
                        exit(EXIT_FAILURE);
                }
        }

        //结束解析
        csv_fini(&p, cb1, cb2, &c);

        fclose(fp);

        printf("%lu fields, %lu rows\n", c.fields, c.rows);

        //释放资源
        csv_free(&p);

        return 0;
}

2.编译源码

$ gcc -o example example.c -lcsv

3.运行结果

$ ./example
1; 2 ; 3      ; 4     ; 5     ; 
1     ; 2   ; 3   ; 4     ; 5     ; 
10 fields, 2 rows
上一篇 下一篇

猜你喜欢

热点阅读