I have a structure called FOO that’s going to be filled with data from a file with columnar data:
JohnDoe 30 60 90 120
JaneDoe 20 40 80 160
...
typedef struct FOO {
char *name;
int *data;
size_t datasize;
} FOO;
…and a function called fillFOO(FILE *fp) that allocates space for and fills this structure with the data from the file. I’ve been trying things like
formatString = myFormatStringBuilder();
and then passing formatString to sscanf in a pretty obtuse way:
fscanf(fi, formatString, pointerToA_FOO->name, pointerToA_FOO->data[0],
pointerToA_FOO->data[1], ...); /* Argh! There has to be an easier way...*/
Is there an easier/cleaner way to read from this file?
easier/cleaner? This line should not work at all:
because the varargs should be l-values.
Also, if there are always 5 columns then you dont need
myFormatStringBuilder()at all:EDIT:
Ok, so the number of columns is not the same for different files. What you can do is this:
First find out how many columns are in the file by reading the first line (ie getline), and counting the number of spaces, then malloc that instead of
4, then for each line:fscanf(fi, "%s", f->name);andfor(int i=0; i<spaces; ++i) { fscanf(fi, "%u", &f->data[i]); }