2012-05-22 181 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

相关问题