2012-05-22 82 views
3

嘗試讀取逗號分隔的數字文件時出現問題,我想要創建一個可以創建整數數組的函數(不知道數組中有多少個參數)在這樣的文件中:從C中的文件中讀取逗號分隔的數字

1,0,3,4,5,2 
3,4,2,7,4,10 
1,3,0,0,1,2 

等等。我要的結果是一樣的東西

int v[]={1,0,3,4,5,2} 

爲文件中的每一行(很明顯,每行的值),所以我可以在這個陣列添加到一個矩陣。我嘗試過使用fscanf,但似乎無法在每行結尾處停下來。我也嘗試過fgets,strtok和我在互聯網上發現的許多其他建議,但我不知道該怎麼做!

我在32位機器上使用Eclipse Indigo。

+1

顯示你當前的代碼,你試過'fgets','strtok'等,這是好的,即使它不工作在所有。所以我們可以從那裏繼續。 –

回答

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

int main(){ 
    FILE *fp; 
    int data,row,col,c,count,inc; 
    int *array, capacity=10; 
    char ch; 
    array=(int*)malloc(sizeof(int)*capacity); 
    fp=fopen("data.csv","r"); 
    row=col=c=count=0; 
    while(EOF!=(inc=fscanf(fp,"%d%c", &data, &ch)) && inc == 2){ 
     ++c;//COLUMN count 
     if(capacity==count) 
      array=(int*)realloc(array, sizeof(int)*(capacity*=2)); 
     array[count++] = data; 
     if(ch == '\n'){ 
      ++row; 
      if(col == 0){ 
       col = c; 
      } else if(col != c){ 
       fprintf(stderr, "format error of different Column of Row at %d\n", row); 
       goto exit; 
      } 
      c = 0; 
     } else if(ch != ','){ 
      fprintf(stderr, "format error of different separator(%c) of Row at %d \n", ch, row); 
      goto exit; 
     } 
    } 
    { //check print 
     int i,j; 
//  int (*matrix)[col]=array; 
     for(i=0;i<row;++i){ 
      for(j=0;j<col;++j) 
       printf("%d ", array[i*col + j]);//matrix[i][j] 
      printf("\n"); 
     } 
    } 
exit: 
    fclose(fp); 
    free(array); 
    return 0; 
} 
3

用下面的代碼,你將CSV存儲到一個多維數組:

/* Preprocessor directives */ 
#include <stdio.h> 
#include <stdlib.h> 

#define ARRAYSIZE(x) (sizeof(x)/sizeof(*(x))) 

const char filename[] = "file.csv"; 
    /* 
    * Open the file. 
    */ 
    FILE *file = fopen(filename, "r"); 
    if (file) 
    { 
     int array[10][10]; 
     size_t i, j, k; 
     char buffer[BUFSIZ], *ptr; 
     /* 
     * Read each line from the file. 
     */ 
     for (i = 0; fgets(buffer, sizeof buffer, file); ++i) 
     { 
     /* 
      * Parse the comma-separated values from each line into 'array'. 
      */ 
     for (j = 0, ptr = buffer; j < ARRAYSIZE(*array); ++j, ++ptr) 
     { 
      array[i][j] = (int)strtol(ptr, &ptr, 10); 
     } 
     } 
     fclose(file); 
+0

非常感謝!我只需要將值保存到一維數組中,該矩陣具有我之前定義的結構。這些功能都可以在stdio中使用?我只能使用那個和stdlib,而且我的教授希望我們最好使用fscanf,是否可以這樣做? –

+0

是的,你有代碼中的預處理器指令... – aleroot

相關問題