Reading comma separated numbers from a file in C

I have a problem trying to read a file with comma numbers, I want to have a function that creates arrays of integers (not knowing how many parameters the array has at the beginning) in a file like this:

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

etc. The result I want is something like

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

for each line of the file (obviously with values ​​in each line), so I can add this array to the matrix. I tried to use fscanf, but I can not get it to stop at the end of each line. I also tried fgets, strtok and many other suggestions that I found on the Internet, but I do not know how to do this!

I am using Eclipse Indigo on a 32-bit machine.

+3
source share
2 answers
#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;
}
+2
source

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);
+3

All Articles