OSDN Git Service

Break out dirtree.c and let it call a function instead of returning the data.
[android-x86/external-toybox.git] / lib / dirtree.c
1 /* vi: set sw=4 ts=4 :*/
2 /* dirtree.c - Functions for dealing with directory trees.
3  *
4  * Copyright 2007 Rob Landley <rob@landley.net>
5  */
6
7 #include "toys.h"
8
9 // Create a dirtree node from a path.
10
11 struct dirtree *dirtree_add_node(char *path)
12 {
13         struct dirtree *dt;
14         char *name;
15
16         // Find last chunk of name.
17         
18         for (;;) {
19                 name = strrchr(path, '/');
20
21                 if (!name) name = path;
22                 else {
23                         if (*(name+1)) name++;
24                         else {
25                                 *name=0;
26                                 continue;
27                         }
28                 }
29                 break;
30         }
31
32         dt = xzalloc(sizeof(struct dirtree)+strlen(name)+1);
33         xstat(path, &(dt->st));
34         strcpy(dt->name, name);
35
36         return dt;
37 }
38
39 // Given a directory (in a writeable PATH_MAX buffer), recursively read in a
40 // directory tree.
41 //
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.
45
46 struct dirtree *dirtree_read(char *path, struct dirtree *parent,
47                                         int (*callback)(struct dirtree *node))
48 {
49         struct dirtree *dt = NULL, **ddt = &dt;
50         DIR *dir;
51         int len = strlen(path);
52
53         if (!(dir = opendir(path))) perror_msg("No %s", path);
54
55         for (;;) {
56                 struct dirent *entry = readdir(dir);
57                 if (!entry) break;
58
59                 // Skip "." and ".."
60                 if (entry->d_name[0]=='.') {
61                         if (!entry->d_name[1]) continue;
62                         if (entry->d_name[1]=='.' && !entry->d_name[2]) continue;
63                 }
64
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);
73                 path[len]=0;
74         }
75
76         return dt;
77 }
78
79