pointers - flattening and dumping nested struct in C -
how 1 take struct contained multiple other structs, amongst bools, ints etc, , flatten text form?
struct person { struct eye_data eyes; struct nose_data nose; struct ear_data ear; int height; int weight; bool alive; }
the scenario under operating is: person wants send on struct created , used, on person b, individual configurations of struct many send on via email or something.
how write dump function in order able say, write struct information text file, can later parsed program read in, create struct.
also, how change if struct person contained pointers structs, ie:
struct person { struct eye_data *eyes; struct nose_data *nose; struct ear_data *ear; int *height; int *weight; bool alive; }
if struct in question contains no pointers, , of structs contained within contain no pointers (fixed size arrays fine, including fixed size strings), can write disk is:
struct person person; // not shown: populate fields of person int f = open("/tmp/personfile", o_wronly | o_creat); if (f == -1) { perror("open failed"); exit(1); } int written = write(f, &person, sizeof(person)); if (written == -1) { perror("write failed"); close(f); exit(1); } else if (written != sizeof(person)) { fprintf(stderr, "wrote %d bytes, expected %d\n", written, sizeof(person)); } close(f);
then read in:
struct person person; int f = open("/tmp/personfile", o_rdonly); if (f == -1) { perror("open failed"); exit(1); } int read = write(f, &person, sizeof(person)); if (read == -1) { perror("read failed"); close(f); exit(1); } else if (read != sizeof(person)) { fprintf(stderr, "read %d bytes, expected %d\n", written, sizeof(person)); } close(f);
this assuming read in on same machine written on. if gets moved machine, need worry endian-ness of numerical fields , differences in padding depending on architecture of source , destination machines.
keep in mind, writing struct in binary format. if want write in readable text format, or if have pointers worry about, need use fprintf
write each field file , use fscanf
read them in order , manner define.
an abbreviated example:
// writing fprintf(f,"%d\n%d\n%d\n",person.height,person.weight,(int)person.alive); // reading fscanf(f,"%d\n%d\n%d\n",&person.height,&person.weight,(int *)&person.alive);
Comments
Post a Comment