CSV到C中的数组 [英] CSV into array in C

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

问题描述

我试图加载一个CSV文件到一个单一的维数组。我可以输出CSV文件的内容,而是在尝试将它复制到我有一点麻烦的数组。

I'm trying to load a CSV file into a single dimentional array. I can output the contents of the CSV file, but in trying to copy it into an array I'm having a bit of trouble.

下面是我现有的code,我意识到可能是pretty坏,但我自学:

Here is my existing code, which I realise is probably pretty bad but I'm teaching myself:

#include <stdio.h>
#include <string.h>

#define MAX_LINE_LENGTH 1024
#define MAX_CSV_ELEMENTS 1000000

int main(int argc, char *argv[])
{
    char line[MAX_LINE_LENGTH] = {0};
    int varCount = 0;
    char CSVArray[MAX_CSV_ELEMENTS] = {0};

    FILE *csvFile = fopen("data.csv", "r");

    if (csvFile)
    {
        char *token = 0;
        while (fgets(line, MAX_LINE_LENGTH, csvFile)) 
        {
            token = strtok(&line[0], ",");
            while (token)
            {
                varCount++;
                CSVArray[varCount] = *token; //This is where it all goes wrong
                token = strtok(NULL, ",");
            }
        }
        fclose(csvFile);
    }
    return 0;
}

有没有更好的办法,我应该这样做呢?在此先感谢!

Is there a better way I should be doing this? Thanks in advance!

推荐答案

*标记表示取消引用指针标记这是 strtok的找到的第一个字符的字符串的地址。这就是为什么你的code填充 CSVArray 只有每个记号的第一个字符。

*token means dereferencing the pointer token which is the address of the first character in a string that strtok found. That's why your code fills CSVArray with just the first characters of each token.

您应该宁愿字符指针数组的标记点,如:

You should rather have an array of char pointers to point at the tokens, like:

char *CSVArray[MAX_CSV_ELEMENTS] = {NULL};

然后指针分配给它的元素:

And then assign a pointer to its elements:

CSVArray[varCount] = token;

另外,你可以在每次复制整个令牌:

Alternatively, you can copy the whole token each time:

CVSArray[varCount] = malloc(strlen(token)+1);
strcpy(CVSArray[varCount], token);

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

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