读取C中的.CSV文件

问题描述:

我回到Java大学的C大学,我们的第一项任务是读取.CSV文件中存在的值,但教科书并不清晰,教授对我们没有太大的帮助。我真的没有很多方向,而且任务很快就会到期,所以我真的需要一些指导!读取C中的.CSV文件

我想我可以通过大多数一切自己搞定了,但我只是不能确定哪些代码块所做的事......

static int extractItems(char *line, char row[][MAXLEN]) { 
    char *item; 
    int col = 0; 
    for(; ;) { 
     item = strtok(line, ",\r\n"); 
     if (item == NULL) 
      break; 
     if (col >= MAXCOLS) { 
      tooWide = 1; 
      break; 
     } 
     strncpy(row[col], item, MAXLEN); 
     row[col][MAXLEN] = '\0'; // force null termination 
     col++; 
     line = NULL; // required by strtok function 
    } 
    return col; 
} 

上校指的是列数,第一个是0

我知道它检查行中是否没有任何内容,是否太宽,但其余的对我来说是陌生的。

我想解释的最好的办法是注释代码:

static int extractItems(char *line, char row[][MAXLEN]) { 
             //line is a char* to your array of chars 
                // - one long string 
             //row is a two dimensional array of chars 
                // - an array of strings 
    char *item; 
    int col = 0; 
    for(; ;) {      //infinite loop, we can exit it with "break" though 
     item = strtok(line, ",\r\n"); //string->token. Returns a pointer to a string, 
             //which is the next token in the input. 
             //it does this by replacing the first character found 
             //from the second string passed (",\r\n") with '\0' 
             //and returning the pointer to where it started 
             //searching from. 
             //i.e. it cuts the string up into substings (tokens) 
             //and returns a pointer to the next one each time 
             //it is called. 
     if (item == NULL)    //if NULL we are at end of the line. so exit loop 
      break; 
     if (col >= MAXCOLS) {   //if we have read too much (reached our limit) then exit 
      tooWide = 1;    //is this a global? anyway it is used to signal that there was too much data 
      break; 
     } 
     strncpy(row[col], item, MAXLEN); //copy the temporary string returned by strtok to the array 
     row[col][MAXLEN] = '\0';  // force null termination (C_string remember?) 
     col++;      // increment the number of words counted 
     line = NULL;     // required by strtok function 
              //passing in NULL gets strtok to continue scanning 
              //from the end of the previous successful scan 
    } 
    return col; 
} 

对strtok的更多信息:this answer describes it well

让我们打破计划和分析,

static int extractItems(char *line, char row[][MAXLEN]) { 

line是一个包含从CSV文件读取的当前行的数组。
row是一个两个维阵列,其中每个项目是从CSV一个单独的元件文件

item = strtok(line, ",\r\n"); 

的strtok功能分割字符串,第一个参数,这里line成基于所述deliminter字符串标记,第二个参数,这里,\n\r 也就是说,如果CSV文件包含一个线
Hello, world 然后subsiquent调用与线函数strtok,产生 Hello =>在分割线, world =>分裂在\ n个线,\ r用作我N个窗口作为新行
For further reading refer this link

现在各个元件在item其由strncpy其复制n,MAXLEN字符到row复制获得。

strncpy(row[col], item, MAXLEN); 
row[col][MAXLEN] = '\0'; 

然后它被\0

col++;      
line = NULL; 

incremennts为下一项目的下一个位置deliminted并设置line到NILL为下一个。

由于数组row作为默认值通过引用传递,一旦程序运行,row将包含CSV文件中每个逗号分隔值。