the problem is pointers. if you accidentally send a pointer to the binary file, it will save that, and load it back, but the pointer it loads back will not have been set up and the data under it will have been lost.
if you do this:
struct s{int x, double d;}
and save it to a binary file, its fine.
if you do this:
struct s2{int x; string z;}
it will not work. it will write the raw binary of the string object to the file, yes, but it stores the hidden pointer inside string to the file, not the character data that is pointer to.
c-string arrays work:
struct s2{int x; char z[maxsizealllowed]};
the binary file will allocate maxsizeallowed bytes and put the data from z into them. Its wasteful, but see the 'time space tradeoff' concept.
the same is true for linked lists. if you save struct list, all you get are 2 pointers that when loaded back are not valid.
there are 2 ways to deal with the issue.
you can serialize your data for read and write to a file, either up front by making your lowest level object C-style and pointer free, or you can reverse your c++ object down to the byte level.
in the specific case of a linked list, what you *really want* is for your binary file to look like this: data0data1data2data3.... where data is the thing the list stores, and the file position is your clue as to 'next' (you don't need head, next, any of that at all, its implied by the order of the data in the file).
so what you can do with what you have is traverse the list from head to tail and send just the data items into the list in a safe binary format.
lets put that in action for a pretend list of c++ string objects which for our made up scenario will have a max string length of 100 ascii letters including the zero terminal for c-strings.
list * lp = head;
char tmp[100];
while(lp) //stops on the ending null entry in the list
{
strcpy(tmp, lp->data.c_str());
filevar.write(tmp, 100);
lp = lp->next;
}
|
there are ways to avoid the copy to array safely, but for the concept, just let the inefficiency ride while absorbing the idea. Avoiding the copy makes the underlying concept less visible in the code.