on Sun, Jul 01, 2001 at 05:12:18AM -0700, David Freeman scribbled:
struct recd { char *name; int someval; }
This is exactly what I have, how would I save the contents of this structure? would I have to save the text into another file and then read the struct file in from one place and the text from else where?
yes, or you could do fprintf/fgets to write/read the data, this also avoids endianness issues (because it's saved/loaded as binary data with fwrite/fread).. If there is only one string, you can still get away with fwrite/fread though.. but you need to be a bit more careful.
struct recd { int someval; char name[0]; };
and dynamically allocate the structure with sizeof(struct recd) + length of name. fprintf/fgets is much more flexible.
struct rec_t { char *fname; char *sname; int age; } rec[MAX_REC];
to save: { int x;
for (x = 0; x < MAX_REC; x++) { if (fprintf(fd, "%s:%s:%d\n", rec[x].fname, rec[x].sname, rec[x].age) > MAX_LINE) warn("line too long"); /* messy */ } }
to load (assuming you don't want any dynamically allocated line buffers and have a max line length): { char buf[MAX_LINE]; int x,len;
x = 0;
while(x <= MAX_REC && fgets(buf, sizeof(buf), fd) != NULL) { len = strchr(buf, ':') - buf;
if (len < 0) err("invalid record: %d", x);
if ((rec[x].fname = malloc(len + 1)) == NULL) err("malloc failed");
memcpy(rec[x].fname, buf, len); rec[x].fname[len] = '\0';
/* repeat for sname and use atoi on age.. */
x++; } if (!feof(fd)) /* error */ return -1; return 1; }
warn(), err() being error spouting functions.. This may not work (small errors in code), but that's basically how I'd do it.. You also need to remember to free() stuff. Yes, you could use fscanf instead of fgets, but then parsing strings containing spaces is harder and dynamically allocating enough memory for strings more troublesome.