Skip to main content
GameDev.net gamedev.net
🔒 Locked

linked list

Started by djsteffey Sep 25, 2000 at 5:25 PM 2 replies 200+ views
Original Post
djsteffey
djsteffey
What do you think is the best way to save and load linked lists from a file. Saving the list is actually the easy part. Just soemthing like
    
Node* temp = myHead;
while(temp){
   outfile.write((char*)&temp->data, sizeof(data));
   temp = temp->link;
}
    
and i believe this will work. but when you are loading from a file, I am thinking that you will need some info at the start of the file to tell how many nodes of data are in the file ? Like have a file header that contains how many items in the list ? Or is there a better way ? "Now go away or I shall taunt you a second time" - Monty Python and the Holy Grail themGames Productions
Ironblayde
Ironblayde
Sounds fine to me... just write the number of elements in the list, followed by the size of a single element in bytes, and then follow that with the list data itself.

-Ironblayde
 Aeon Software

Edited by - Ironblayde on September 25, 2000 6:36:35 PM
"Your superior intellect is no match for our puny weapons!"
Incommunicado
Incommunicado
You could write some sort of file header, as you already pointed out. Another possibility (it just came to my mind when I read your post) is to store some sort of flag for each linked-list element telling whether there is another element appended. This way you could even attach new elements to the file without having to rewrite the whole fileheader, by just changing the flag of the last element. You need just a byte stored at the end of each element and if you append an element to the file just change the last byte in the file to ''1'' or something like this.
Fileheader of course is also a good way. As I said just an idea I had.
felisandria
felisandria
I can think of a couple of ways without counting nodes...

while(!EOF) can work, as long as you know you won''t get the EOF character in your file by accident (I believe EOF is hex 0A). Whether or not you can count on this depends on your data. Another thing you can do is put a few characters to indicate the end, which some audio formats do. Similarly, you can have an "end node" indicator, which is the size of a node but contains all zeros or all F''s or something equally unlikely to appear in a "real" node to indicate.

-fel
~ The opinions stated by this individual are the opinions of this individual and not the opinions of her company, any organization she might be part of, her parrot, or anyone else. ~

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.