views:

80

answers:

3

Hi,

How can I make a copy of a tree data structure in memory to disk in C programming language?

+3  A: 

You need to serialize it, i.e. figure out a way to go through it serially that includes all nodes. These are often called traversal methods.

Then figure out a way to store the representation of each node, together with references to other nodes, so that it can all be loaded in again.

One way of representing the references is implicitly, by nesting like XML does.

unwind
A: 

Come up with a serialization (and deserialization) function. Then run it and send the output to a file.

Nathon
+2  A: 

The basic pieces here are:

  • The C file I/O routines are fopen, fwrite, fprintf, etc.
  • Copying pointers to disk is useless, since the next time you run all those pointer values will be crap. So you'll need some alternative to pointers that still somehow refers disk records to each other. One sensible alternative would be file indexes (the kind used by your C I/O routines like fseek and ftell).

That should be about all the info you need to do the job.

Alternatively, if you use an array-based tree (with array indexes instead of pointers, or with the links implied by their position in the array) you could just save and load the whole shebang without any further logic required.

T.E.D.