I have a data structure in c that is an array of struct pointers:
struct trex *trex_arr[128];
struct trex{
struct trex *next;
char name[LEN];
unsigned int id;
int groups[LEN];
struct list *filenames; //linked list
unsigned int fn_len;
};
I want to write the array to file. I understand that I need to write the object in the “next” pointer and each element in the linked list as well, but how do I do it so that I can read it back successfully into my original array (there is chaining in the array as well)?
Offhand, the simplest way to do it is to write the structure out sequentially so that:
(Of course, this is just sort of the jist of it. These are binary writes and this is a visual only.)
I’m hoping that
fn_lendescribes the number of items in the linked liststruct list *filenames. If so, this is a snap.On writing:
trexlinked liststruct list *filenamesfrom that firsttrexstructure one at a timetrexlinked list until the list is exhausted.On reading, remember: all of your pointers are going to be worthless initially. You have to stitch them together yourself. But the structures are arranged in the correct order in the file.
trexstructure. You know its size, reading it isn’t a problem. Fix thenextpointer to nothing.struct list *filenamesone at a time. You know how many they are because offn_lenin the structure you just read. Stitch together that linked list and attach it to the trex structure.trexstructure until EOF, join the structure onto the end of the linked list as appropriate.And that should take care of it.