Read data into a float array in C
i am making a开发者_StackOverflow program where i need to load some floating point data of the format from a file
103.45 123.45 456.67 ......i was wondering how to store these data directly into a array of floating point numbers using fread(). i guess it is not that hard using pointers but i am not so good with them. can anyone tell me how
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);
Not sure what else you need, but this solves the essence of the problem:
int j = 0;
double flts [20000];
while (!feof(f))
{
if (fscanf (f, "%g", &flts [j]) == 1)
++j; // if converted a value okay, increment counter
}
You can't use fread
as that doesn't parse the form of file that you have. fread
just reads bytes into an array of bytes and what you have is numbers written out in a human readable decimal form.
I think that for this format the most direct way that you can use is to use fscanf
in a loop, being sure to check the return value and, on failure, ferror
and/or feof
to check whether you hit the end of file or some other error.
you can't unless your data file is in binary fromat. You are showing a plaint text file: in order to get that into an array, you will need to do a couple of things: find out how much items needed in the array (number of lines?), allocate the array, then convert and put each value in the array. Conversion can be done using scanf for example.
Since this looks like a file with ASCII in it I post the following strategy. However you seem to be suggesting that the file contains binary data. This assumption is based on the fact that you are trying to read it with fread().
Keep reading a line at a time from the file, and parse the string input from the file into a float, do this until the file returns EOF.
精彩评论