将字符串的CSV文件解析为2d字符串数组

时间:2016-06-09 20:17:29

标签: c arrays csv

我有一个字符串的CSV,如下所示:

"","Orange","","","","","","Red",""
"Orange","","Blue","","","","","Black",""
"","Blue","","Pink","","Any","","","Any"
"","","Pink","","Green","Red","","",""
"","","","Green","","Blue","","",""
"","","Any","","BLue","","Orange","",""
"","","","Red","","Orange","","Green","Black"
"Red","Black","","","","","Green","","Yellow"
"","","Any","","","","Black","Yellow",""

我想把它放到一个2d的字符串数组中(我稍后会忽略引号)。我尝试了很多不同的想法,但似乎无法正常工作。

此代码已关闭,但输出以我无法理解的方式关闭。它还可以正确地解析和标记文件。当它将令牌放入数组时似乎变坏了。以下是从我的程序中获取的代码:

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

 #define VERTICES 9

 int main(void)
 {
     const char *colors[VERTICES][VERTICES];

     char buffer[1024];
     char *record, *line;
     int i = 0;
     int j = 0;
     FILE *fstream = fopen("Colors.dat", "r");
     if (fstream == NULL)
     {
         printf("\n file opening failed\n");
         return -1;
     }
     while ((line = fgets(buffer, sizeof(buffer), fstream)) != NULL)
     {
         record = strtok(line, ",");
         while(record != NULL)
         {
             printf(" %s", record);
             colors[i][j] = record;
             //printf(" %s"), colors[i][j];
             record = strtok(NULL, ",");
             j++;
         }
         j = 0;
         ++i;
     }

     printf("\n============================================\n\n");

     for (i = 0; i < VERTICES; i++)
     {
             for (j = 0; j < VERTICES; j++)
             {
                 printf("%s | ", colors[i][j]);
             }
         printf("\n");
     }
     return 0;
 }

如果取消注释第二个嵌套while循环中的行并注释掉两个for循环,你也会得到奇数输出。谢谢!

1 个答案:

答案 0 :(得分:1)

OP很容易记录读缓冲区的地址,后续读取时会更新。

需要分配/复制字符串以供日后使用。

// colors[i][j] = record;
colors[i][j] = strdup(record);

一行中剩余的colors[i][j]应设置为NULL

     while(j < VERTICES && record != NULL) {
         printf(" %s", record);
         colors[i][j] = strdup(record);
         assert(colors[i][j]);
         record = strtok(NULL, ",");
         j++;
     }
     while(j < VERTICES) {
         colors[i][j] = NULL;
         j++;
     }

强大的代码也会检查分配失败(assert(colors[i][j]),并在完成后释放memroy。