将.csv文件读入C语言的数组中 [英] Reading .csv file into an array in C

查看:1481
本文介绍了将.csv文件读入C语言的数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am Currently trying to read a .csv file into an array in C. I'm somewhat on the fence on how to approach the problem. I've looked through many forums and related topic but I still can't grasp it. If someone could show me or break it down as simple as possible. That would be greatly appreciated. By the way, the contents of the .csv file is like this. The array should consist of just the alphabet and the number. I was thinking about using a 2-D array. Is that an appropriate solution?

A,1
B,2
C,3
....

推荐答案

首先定义数据结构:

struct my_record {
    char name;
    int value;
};

然后您可以阅读如下内容:

Then you can read like this:

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);

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

Now you have a 1D array of structs, one for each row.

这篇关于将.csv文件读入C语言的数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆