To read the data from the file use fgets()
and sscanf()
.
/* needs validation and error checking */
fgets(buf, sizeof buf, fp);
sscanf(buf, "%f", &tmp);
To manage the number of floats, you have two options.
- use an array of fixed size
- use
malloc()
, realloc()
and friends for a growable array
/* 1. use an array of fixed size */
float array[1000];
/* 2. use `malloc()`, `realloc()` and friends for a growable array */
float *array;
array = malloc(1000 * sizeof *array);
/* ... start loop to read floats ... */
if (array_needs_to_grow) {
float *tmp = realloc(array, new_size);
if (tmp == NULL) /* oops, error: no memory */;
array = tmp;
}
/* end reading loop */
/* ... use array ... */
free(array);