C语言读取csv文件并保存到二维数组

发布时间 2023-09-02 21:33:52作者: C羽言

 

#include <stdio.h>
#include <string.h>
#include <time.h>
#define MAXCHAR 1024
#define MAXCOUNT 1000000
char *mat[MAXCOUNT][9]; // 如果放到main里面会有长度限制使应用程序退出,放在外面作为全局变量没有限制。

int main()
{
    clock_t start, end;
    start = clock();

    FILE *fp;
    char row[MAXCHAR];
    char *token;

    fp = fopen("big.csv", "r");
    int linecount = 0, i = 0, j = 0;

    while (fgets(row, MAXCHAR, fp))
    {
        linecount++;
        if (linecount == 1)
            continue; // Skip first line

        if (linecount - 1 > MAXCOUNT) // 实际输出的行数 要去掉上面跳过的1行
            break;

        token = strtok(row, ",");
        j = 0;
        while (token)
        {
            // printf("Token: %s\n", token);
            // printf("i=%d,j=%d\n", i, j);
            mat[i][j++] = strdup(token);
            token = strtok(NULL, ",");
        }
        i++;
    }
    fclose(fp);

    // for (int i = 0; i < MAXCOUNT; i++)
    // {
    //     for (int j = 0; j < 9; j++)
    //     {
    //         printf("mat[%d][%d]=%s\n", i, j, mat[i][j]);
    //     }
    // }

    puts(mat[405000][3]);

    end = clock();
    printf("time=%f\n", (double)(end - start) / CLOCKS_PER_SEC); // 读取速度跟python的pandas差不多
    return 0;
}

相关资料:

https://stdin.top/posts/csv-in-c/

https://stackoverflow.com/questions/20013693/read-csv-file-to-a-2d-array-on-c