将.csv文件读入C中的数组

mac*_*mac 4 c csv parsing

我目前正在尝试将 .csv 文件读入 C 中的数组。我对如何解决这个问题有些犹豫。我浏览了许多论坛和相关主题,但我仍然无法理解。如果有人可以向我展示或尽可能简单地分解它。这将不胜感激。顺便说一下,.csv文件的内容是这样的。该数组应仅包含字母和数字。我正在考虑使用二维数组。这是一个合适的解决方案吗?

A,1
B,2
C,3
....
Run Code Online (Sandbox Code Playgroud)

Joh*_*nck 5

首先定义你的数据结构:

struct my_record {
    char name;
    int value;
};
Run Code Online (Sandbox Code Playgroud)

然后你可以这样读:

FILE* my_file = fopen(...);
struct my_record records[100];
size_t count = 0;
for (; count < sizeof(records)/sizeof(records[0]); ++count)
{
    int got = fscanf(my_file, "%c,%d", &records[count].name, &records[count].value);
    if (got != 2) break; // wrong number of tokens - maybe end of file
}
fclose(my_file);
Run Code Online (Sandbox Code Playgroud)

现在您有一个一维结构数组,每行一个。