3

コンマ区切りの数値を含むファイルを読み込もうとすると問題が発生します。次のようなファイルに整数の配列を作成する関数が必要です (最初は配列に含まれるパラメーターの数がわからない)。

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 を使用しています。

4

2 に答える 2

3
#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;
}
于 2012-05-22T22:56:18.437 に答える
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);
于 2012-05-22T20:41:58.673 に答える