2014-09-24 87 views
1

我回到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

我知道它檢查行中是否沒有任何內容,是否太寬,但其餘的對我來說是陌生的。

回答

1

我想解釋的最好的辦法是註釋代碼:

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

0

讓我們打破計劃和分析,

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文件中每個逗號分隔值。