1 /* vi: set sw=4 ts=4 :*/
2 /* dirtree.c - Functions for dealing with directory trees.
4 * Copyright 2007 Rob Landley <rob@landley.net>
9 // Create a dirtree node from a path.
11 struct dirtree *dirtree_add_node(char *path)
16 // Find last chunk of name.
19 name = strrchr(path, '/');
21 if (!name) name = path;
23 if (*(name+1)) name++;
32 dt = xzalloc(sizeof(struct dirtree)+strlen(name)+1);
33 xstat(path, &(dt->st));
34 strcpy(dt->name, name);
39 // Given a directory (in a writeable PATH_MAX buffer), recursively read in a
42 // If callback==NULL, allocate tree of struct dirtree and
43 // return root of tree. Otherwise call callback(node) on each hit, free
44 // structures after use, and return NULL.
46 struct dirtree *dirtree_read(char *path, struct dirtree *parent,
47 int (*callback)(struct dirtree *node))
49 struct dirtree *dt = NULL, **ddt = &dt;
51 int len = strlen(path);
53 if (!(dir = opendir(path))) perror_msg("No %s", path);
56 struct dirent *entry = readdir(dir);
60 if (entry->d_name[0]=='.') {
61 if (!entry->d_name[1]) continue;
62 if (entry->d_name[1]=='.' && !entry->d_name[2]) continue;
65 snprintf(path+len, sizeof(toybuf)-len, "/%s", entry->d_name);
66 *ddt = dirtree_add_node(path);
67 (*ddt)->parent = parent;
68 if (callback) callback(*ddt);
69 if (entry->d_type == DT_DIR)
70 (*ddt)->child = dirtree_read(path, *ddt, callback);
71 if (callback) free(*ddt);
72 else ddt = &((*ddt)->next);