从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。

 #include  #include  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 

使用以下代码,您将CSV存储到多维数组中:

 /* Preprocessor directives */ #include  #include  #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);