--- Steve Fosdick fozzy@pelvoux.demon.co.uk wrote:
On Sat, Jun 30, 2001 at 04:53:58PM -0700, David Freeman wrote:
C wizards,
If I write a structure to disk using fwrite(), what happens about pointers to structers? does the pointer or what its pointing at get saved?
The write function takes a pointer and writes out to disk whatever that pointer points to. You also have to tell it how big that item is.
I get this bit.
Imagine you have a structure liek this:
struct recd { name[10]; int some_value; }
If you define a variable of this structure type directly, like this:
struct recd myrecd;
then you need to the use '&' operater to give fwrite a pointer to it, like this:
fwrite(&myrecd, sizeof(myrecd), 1, fp);
If you have a pointer to a structure of this type, like this:
struct recd *myrecptr;
and that pointer points to some valid memory then you can write the structure to disk by calling fwrite with the pointer directly, like this:
fwrite(myrecptr, sizeof(*myrecptr), 1, fp);
Note the '*' in the sizeof operator - we want the size of the thing pointed to (the structure) not the size of the pointer. If you were to make the mistake of using the:
fwrite(&myrecdptr, sizeof(myrecdptr), 1, fp);
form when myrecptr was a pointer then you would indeed write the pointer to the disk instead of the structure pointed too and this is almost never useful.
This all makes sense.
The other catch you need to be wary of is strings in structures. In the example above I used a fixed length string, so the space for the characters of the string is within the structure. This is fine for short strings but for longer ones it is more usual to have:
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?
In this case all that is store in the structure is a pointer to where the string is actually stored. If you write this kind of structure to disk you would get the pointer to the string written to disk as part of the structure but not the contents of the string.
How would I get the contents of the string?
Thanks
D
Steve.
alug, the Anglian Linux User Group list Send list replies to alug@stu.uea.ac.uk http://www.anglian.lug.org.uk/ http://rabbit.stu.uea.ac.uk/cgi-bin/listinfo/alug See the website for instructions on digest or unsub!
__________________________________________________ Do You Yahoo!? Get personalized email addresses from Yahoo! Mail http://personal.mail.yahoo.com/