
How Do I fwrite() and fread() A Structure that contains pointers to dynamic data
Quote:
>I have a question, I hope you can help.
>I need to use binary mode, and I am trying to save a structure that
>contains a couple of pointers to
>dynamicaly allocated data. Example
>struct S {
> int val1;
> float *val2;
> int *val3;
> int val4;
>};
> struct S s;
> val1 = 1;
> val2 = new float[42]; // I use a couple of C++ features : )
> val3 = new int[10];
> val4 = 9;
> // I initialize the pointers with data here.....Then
> fwrite(&s, sizeof(struct S), 1, out);
> I have tried this different ways, and I have tried just writing the
>pointer:
You've created three distinct objects here (one structure and two arrays).
so you'll need three writes to save them out.
fwrite(&s, sizeof s, 1, out);
fwrite(s.val2, sizeof *s.val2, 42, out);
fwrite(s.val3, sizeof *s.val3, 10, out);
If the sizes of the arrays aren't fixed you'll have to save those out
as well, perhaps as extra members of the structure. You should always check
for failure on file I/O. fwrite() returns the number of ``array'' elements
successfully written, that wil be equal to the value of the 3rd parameter
if the write is successful. A short write indicates sone form of failure.
...
Quote:
> When I read the structure back in, val1 is ok, but val2 and val3 are
>garbage! Nothing seems to work. Can you help?
When you read the data back in you must create the objects to hold the data
first and set up the pointer links yourself. Pointer values stored in files
are generally meaningless, the only refer to the original objects in the
original environment that wrote the data out. To read the data back in you
might use code of the form:
struct S s;
fread(&s, sizeof s, 1, in);
val2 = new float[42]; /* I'll let this pass this time! */
val3 = new int[10];
These set the pointers in s up. val2 and val3 need to be assigned after
the initial fread() or it will just overwrite them.
fread(s.val2, sizeof *s.val2, 42, in);
fread(s.val3, sizeof *s.val3, 10, in);
Again, you should test for input failure. fread()'s return is the same as
fwrite()'s except that a ``short'' read may indicate end-of-file as opposed
to an error condition.
--
-----------------------------------------
-----------------------------------------