Tuesday, 15 March 2011

file io - Building a format string in C -



file io - Building a format string in C -

i have construction called foo that's going filled info file columnar data:

johndoe 30 60 90 120 janedoe 20 40 80 160 ... typedef struct foo { char *name; int *data; size_t datasize; } foo;

...and function called fillfoo(file *fp) allocates space , fills construction info file. i've been trying things like

formatstring = myformatstringbuilder();

and passing formatstring sscanf in pretty obtuse way:

fscanf(fi, formatstring, pointertoa_foo->name, pointertoa_foo->data[0], pointertoa_foo->data[1], ...); /* argh! there has easier way...*/

is there easier/cleaner way read file?

easier/cleaner? line should not work @ all:

fscanf(fi, formatstring, pointertoa_foo->name, pointertoa_foo->data[0], ...

because varargs should l-values.

also, if there 5 columns dont need myformatstringbuilder() @ all:

foo* f = malloc(sizeof(foo)); f->name = malloc(100); // or whatever f->data = malloc(4*sizeof(int)); fscanf(fi, "%s %u %u %u %u", f->name, &f->data[0], &f->data[1], &f->data[2], &f->data[3]);

edit: ok, number of columns not same different files. can this: first find out how many columns in file reading first line (ie getline), , counting number of spaces, malloc instead of 4, each line: fscanf(fi, "%s", f->name); , for(int i=0; i<spaces; ++i) { fscanf(fi, "%u", &f->data[i]); }

c file-io format

No comments:

Post a Comment