Search code examples
cserializationdata-structurestreefwrite

how to write tree data to file in C?


I was looking at the similar questions but didn't find a solution . I have a structure similar to a tree with more than 2 nodes. I also have a pointer to the root.

typedef struct tree
{
   char *name;
   struct tree *children
}TREE;

I want to write this data to a file , but just got confused so would love to get some help

I thought using :

int writeData(TREE *root , char *filename){

    FILE *f = NULL;
    int numWritten = 0;

fopen_s(&f , filename, "w+" );
fwrite(root , sizeof(TREE) , ??? , f);

}

I don't know what to write, how can If I have children to every element so I beed to go threw them all - how can I do that?


Solution

  • Well, this problem is known as 'serializing structured data' - basically it's the opposite of parsing. The thing is that you can't just dump the raw binary data of your in-memory data structure to a file - it won't be meaningful upon the next launch of your program when addresses change. You have to come up with a format that is able to describe your data structure and write that to the file. Then, of course, you'll also have to write a parser for that format if you want to recover the data structure from the file later.

    I suggest using JSON - it's a lightweight, easy-to-write and easy-to-read data format, and it's also general-purpose - it's ideal to store simple abstract data types. Here's my library that can generate and parse JSON from basic data types (such as arrays, associative arrays, strings, numbers...)

    how can If I have children to every element so I beed to go threw them all

    For this question: you're probably looking for recursion. You'll need to recursively traverse your data tree and generate the data representing your data structure as you walk by each node/leaf (assuming your data structure being similar to a graph/tree).