Mail Archives: djgpp/1997/08/22/17:36:32
Kertis A. Henderson wrote:
>
> Under djgpp, what is the best way to write a bunch of structs to a
> file? For instance, I'd like to write a linked list to a file node by
> node, then be able to read the nodes back and reconstruct the list. A
> node could be something like the following:
>
> struct node {
> int number;
> unsigned char age;
> char *name;
> node *next;
> }
>
> The ints and chars would be relatively easy, but I don't see how a
> variable length string could be written. Of course, the node pointer
> wouldn't be written.
>
> If anybody could help me out (or possibly point me in the right
> direction), I'd appreciate it. Thanks for any input.
What about this:
int sl;
...
sl= strlen(nd->name);
fwrite(&sl,1,sizeof(sl),f);
fwrite(nd->name,sl,sizeof(char),f);
...
Read:
int sl;
...
fread(&sl,1,sizeof(sl),f);
nd->name = malloc(sl);
fread(nd->name,sl,sizeof(char),f);
Check the order of parameters of fwrite() and and fread(), because
I usually mix them up...
--
Ciao
Tom
*************************************************************
* Thomas Demmer *
* Lehrstuhl fuer Stroemungsmechanik *
* Ruhr-Uni-Bochum *
* Universitaetsstr. 150 *
* D-44780 Bochum *
* Tel: +49 234 700 6434 *
* Fax: +49 234 709 4162 *
* http://www.lstm.ruhr-uni-bochum.de/~demmer *
*************************************************************
- Raw text -