简体   繁体   English

通过使用strsep拆分来解析CSV文件

[英]Parsing CSV file by splitting with strsep

I'm getting some unwanted output when attempting to parse a comma seperated value file with strsep(). 尝试使用strsep()解析逗号分隔值文件时,我收到了一些不需要的输出。 It seems be be working for half of the file, with a number with only one value (ie. 0-9), but as soon as multiple values are added like for instance 512, 它似乎对文件的一半有效,只有一个值只有一个值(即0-9),但只要添加了多个值,例如512,

It will print 512 12 2 512 12 2 and so on. 它将打印512 12 2 512 12 2,依此类推。 I'm not exactly sure if this is due to the particular style that I'm looping? 我不确定这是否是由于我正在循环的特定风格? Not really sure. 不太确定。

int main() {

        char line[1024];

        FILE *fp;

        int data[10][10];

        int i = 0;
        int j = 0;

        fp = fopen("file.csv", "r");

        while(fgets(line, 1024, fp)) {

                char* tmp = strdup(line);
                char* token;
                char* idx;

                while((token = strsep(&tmp, ","))) {

                        for (idx=token; *idx; idx++) {
                                data[i][j] = atoi(idx);
                                j++;
                        }
                }
                i++;
                j=0;

                free(tmp);

        }


         for(i = 0; i < 10; i++) {

                for(j = 0; j < 10; j++) {
                printf("%d ", data[i][j]);
                }
                printf("\n");
        }

        fclose(fp);
}

It is because you are creating elements by using every characters in the token returned by strsep() as start via the loop 这是因为您通过使用strsep()返回的标记中的每个字符作为循环开始来创建元素

for (idx=token; *idx; idx++) {
        data[i][j] = atoi(idx);
        j++;
}

Stop doing that and create just one element from one token to correct: 停止这样做并从一个标记创建一个元素来纠正:

while((token = strsep(&tmp, ","))) {

        data[i][j] = atoi(token);
        j++;
}

Also free(tmp); free(tmp); will do nothing because tmp will be set to NULL by strsep() . 什么都不会因为strsep()tmp设置为NULL To free the buffer allocated via strdup() , keep the pointer in another variable and use it for freeing. 要释放通过strdup()分配的缓冲区,请将指针保存在另一个变量中并将其用于释放。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM