2015-01-21 84 views
0

我需要編寫一個程序來解析C中的大型CSV文件(大約2000 * 2000),並以double [] []數組的形式進行存儲。我寫了一個程序,它似乎適用於小文件(我檢查了一個4 * 4的csv文件),但是對於大文件,它給了我不正確的結果(如行和列的數目是錯誤的,程序崩潰後那)。將CSV文件讀取到C中的2D雙數組中

這是代碼:

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

int main (void) 
{ 
    int rowMaxIndex,columnMaxIndex; 
    double **mat; 
    double *matc; 
    int i,j,idx,len; 
    char part[5000]; 
    char *token; 
    char *temp; 
    char *delim = ","; 
    double var; 
{ 
    FILE *fp; 
    fp = fopen("X1_CR2_new1.csv","r"); 

    if(fp == NULL) 
    { 
     perror("Error while opening the file.\n"); 
     exit(EXIT_FAILURE); 
    } 

    // count loop 
    rowMaxIndex = 0; 
    columnMaxIndex = 0; 
    while(fgets(part,5000,fp) != NULL){ 
     token = NULL; 
     token=strtok(part,delim); 
        while(token != NULL){ 
         if(rowMaxIndex==0) 
         { 
         columnMaxIndex++;} 
         token=strtok(NULL,delim); 
     } 
     rowMaxIndex++; 
    } 
    fclose(fp); 

    printf("Number of rows is %d, and Number of columns is %d", rowMaxIndex, columnMaxIndex); 
    // allocate the matrix 

    mat = malloc(rowMaxIndex * sizeof(double*)); 

    for (i = 0; i < rowMaxIndex; i++) 
    { 
     mat[i] = malloc(columnMaxIndex * sizeof(double)); 
     } 
     fclose(fp); 
} 
    // rewind the file to the beginning. The rewind(fp) wasnt working so closed and reopened file. 

{ 
    FILE *fp; 
    fp = fopen("X1_CR2_new1.csv","r"); 

    if(fp == NULL) 
    { 
     perror("Error while opening the file.\n"); 
     exit(EXIT_FAILURE); 
    } 

    // read loop 
    i = j = 0; 
    while(fgets(part,5000,fp)!=NULL) 
    {  
     token=strtok(part,delim); 
     j=0; 
     while (token != NULL){ 
       mat[i][j]=atof(token); 
       //printf("\n %f", mat[i][j]); 
       token=strtok(NULL,delim); 
       j++; 
      } 
     i++; 
    } 
    printf("\n The value of mat 1, 2 is %f", mat[1][0]); //print some element to check 
    free(mat); 
    fclose(fp); 
}  

    return 0; 
} 
+0

嘗試調試代碼:http://ericlippert.com/2014/03/05/how-to-debug-small-programs/ – alk 2015-01-21 06:51:59

回答

2

你說你的數據有2000列,但您fgets()讀取最多4999個字符。你的數據是不是有可能超過4999個字符?您應該檢查每行讀入的內容是否包含換行符(文件中最後一行除外)。

順便說一句,你不需要重新打開該文件 - 它只是rewind()它。

+1

或者,更簡單,使用POSIX ['函數getline()'](HTTP: //pubs.opengroup.org/onlinepubs/9699919799/functions/getline.html), 它總是返回一個完整的行,除非它不能分配足夠的內存。 – 2015-01-21 05:30:01

+0

謝謝。改爲20000字符,現在工作正常。但是,嘗試了rewind(),但它沒有返回到文件的開頭。我不知道爲什麼。 Getline不包含在我的默認包中,所以沒有使用。 – 2015-01-22 16:01:14