user1386966
user1386966

Reputation: 3402

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?

Upvotes: 2

Views: 2446

Answers (2)

Paddy3118
Paddy3118

Reputation: 4772

You could copy the working data structure so that all used TREEs are stored in an array of TREEs and change all TREE pointers to be indices into the array then store the whole array of TREEs in a binary file. Oh, The char pointers would have to be pointers into a single array of characters that is stored, also.

Not as readable as YAML or JSON, but if you needed a binary format ...

Upvotes: 0

user529758
user529758

Reputation:

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).

Upvotes: 5

Related Questions