Saving array of structs to file

This is a discussion on Saving array of structs to file within the C++ Programming forums, part of the General Programming Boards category; My program deals with the following structs: Code: struct NodeType { bool IsQuestion; string info; NodeType* right; NodeType* left; }; ...

  1. #1
    Registered User
    Join Date
    May 2002
    Posts
    21

    Saving array of structs to file

    My program deals with the following structs:
    Code:
    struct NodeType
    {
    	bool IsQuestion;
    	string info;
    	NodeType* right;
    	NodeType* left;
    };
    which is actually a node in a binary tree.
    I want now to save this binary tree to a file as an array and then recover it when the program starts again.
    I tried fread() and fwrite(), but the program crashes, probably because these functions doesn't know how to handle string.

    Can someone suggest me a way of doing this?

  2. #2
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    > NodeType* right;
    > NodeType* left;

    I think this is the problem. These are pointers which are dynamically allocated at runtime. Once your program quits, and is restarted, your program is loaded into another section of memory, and these pointers are no longer valid.

    I'm not sure what the solution would be.

  3. #3
    Registered User
    Join Date
    May 2002
    Posts
    21
    You're right. The error is on these pointers. I created an additional struct type and replace string with char*:
    [CODE ]
    struct ArrayNode
    {
    bool IsQuestion;
    char *info;
    }
    [/CODE]
    and I used natural mapping for the conversion. Now it works fine.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. File transfer- the file sometimes not full transferred
    By shu_fei86 in forum C# Programming
    Replies: 13
    Last Post: 03-13-2009, 12:44 PM
  2. Can we have vector of vector?
    By ketu1 in forum C++ Programming
    Replies: 24
    Last Post: 01-03-2008, 04:02 AM
  3. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  4. System
    By drdroid in forum C++ Programming
    Replies: 3
    Last Post: 06-28-2002, 10:12 PM
  5. simulate Grep command in Unix using C
    By laxmi in forum C Programming
    Replies: 6
    Last Post: 05-10-2002, 04:10 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21