Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read comma separated numbers from a file in C

Tags:

c

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

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

and so on. The result I want is something like

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

for every line in the file (obviously with the values in each line) so I can add this array to a matrix. I tried using fscanf, but I can't seem to make it stop at the end of each line. I also tried fgets, strtok, and many other suggestions I found on the Internet, but I don't know how to do it!

I'm using Eclipse Indigo in a 32-bit machine.

like image 357
PL-RL Avatar asked Dec 22 '25 23:12

PL-RL


1 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;
}
like image 85
BLUEPIXY Avatar answered Dec 24 '25 17:12

BLUEPIXY



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!