How to read comma separated numbers from a file into an multidimensional array in C

StackOverflow https://stackoverflow.com/questions/14608754

  •  06-03-2022
  •  | 
  •  

Pregunta

I want to write a function that creates arrays of integers in a file with comma separated numbers like this:

         1,    54520.00000,    86397.00000,   0
         2,    54440.00000,    87200.00000,   0
         3,    51280.00000,    97600.00000,   0
         4,    50000.00000,   100000.00000,   0
         5,    48880.00000,   100000.00000,   0

The first column is the number of each row, so the data I need is actually the next three columns.
My problems are:

  1. Since I don't know the dimension of the array, I have to first read the first number of the last row. How to do that? I tried to use fseek to point my file pointer to the end of the file and then find the previous '\n', but I don't know how to deal with comma.
  2. After I get the number of rows, how can I read those data I need into a N_row*3 array? How to deal with comma and '\n'?

Thanks for your help in advance!

¿Fue útil?

Solución

you can use fscanf()

use the following fscanf() into a loop till you reach the end of the file:

int i,j
double x,y;
while (fscanf(fp, " %d , %f , %f , %d", &i, &x, &y, &j) != EOF) {....}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top