Revised tree
I have to make some changes in tree.c and tree.h, so del_branchcan be implemented easily!
Code:
tree.h
#ifndef GKO_TREE_H
#define GKO_TREE_H
#include "stack.h"
#include "common.h"
struct branch {
char *name;
char *data;
struct branch *cont;
struct branch *next;
} branch;
void init_tree (struct branch *, char *, char *) ;
void set_branch (struct branch *, char *, char *);
struct branch * get_branch (struct branch *, char *);
void del_branch (struct branch *);
#endif
tree.c
#include "tree.h"
/* Initialize a Tree, set the root node */
void
init_tree (struct branch *t, char *name, char *data)
{
cpystr (&t->name, name);
cpystr (&t->data, data);
t->cont = NULL;
t->next = NULL;
}
/* Create a new struct branch or edit an existent one */
void
set_branch (struct branch *t, char *name, char *data)
{
struct branch *b;
struct branch *prior;
if (!t || !name || !data)
pexit ("set_branch: NULL argument call\n");
for (b = t->cont, prior = NULL; b; prior = b, b = b->next) {
if (! strcmp (b->name, name)) {
free (b->data);
cpystr (&b->data, data);
return;
}
}
b = xmalloc (sizeof (struct branch));
init_tree (b, name, data);
if (!prior) /* if there is no content in branch *t, the prior remains NULL */
t->cont = b;
else
prior->next = b;
}
/* Return the address of a struct branch */
struct branch *
get_branch (struct branch *t, char *name)
{
struct branch *b;
if (!t || !name)
pexit ("get_brach: NULL argument call\n");
for (b = t->cont; b; b = b->next)
if (! strcmp (b->name, name))
return b;
return NULL;
}
/* Delete a struct branch an everything below that node */
void
del_branch (struct branch *t)
{
if (t->cont)
del_branch (t->cont);
if (t->next)
del_branch (t->next);
free (t->name);
free (t->data);
free (t);
}
common.c
#include "common.h"
void
pexit (const char *msg)
{
perror (msg);
exit (EXIT_FAILURE);
}
void *
xmalloc (size_t siz)
{
void *n = malloc (siz);
if (!n)
pexit ("malloc");
return n;
}
void
cpystr (char **dst, char *src)
{
int len = strlen (src) + 1;
*dst = xmalloc (len);
strncpy (*dst, src, len);
}
test.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "tree.h"
main ()
{
struct branch *myt = xmalloc (sizeof (struct branch));
struct branch *buf;
init_tree (myt, "root", "root_data");
set_branch (myt, "etc", "etc_data");
set_branch (myt, "usr", "usr_data");
buf = get_branch (myt, "etc");
set_branch (buf, "rc.conf", "rc.conf data");
set_branch (myt, "etc", "etc_edited_data");
del_branch (myt);
return 0;
}