changeset 95:a636e4d20f13

Add xstat(), read_dirtree(), and read_dirtree_node().
author Rob Landley <rob@landley.net>
date Sat, 03 Feb 2007 14:11:26 -0500
parents 884c03c29f21
children 05d109d4acb9
files lib/functions.c lib/lib.h
diffstat 2 files changed, 76 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/lib/functions.c	Sat Feb 03 14:10:00 2007 -0500
+++ b/lib/functions.c	Sat Feb 03 14:11:26 2007 -0500
@@ -251,6 +251,11 @@
 	return buf;
 }
 
+void xstat(char *path, struct stat *st)
+{
+	if(stat(path, st)) perror_exit("Can't stat %s\n",path);
+}
+
 // Cannonicalizes path by removing ".", "..", and "//" elements.  This is not
 // the same as realpath(), where "dir/.." could wind up somewhere else by
 // following symlinks.
@@ -495,3 +500,64 @@
 	xwrite(fd, spid, sprintf(spid, "%ld\n", (long)getpid()));
 	close(fd);
 }
+
+// Create a dirtree node from a path.
+
+struct dirtree *read_dirtree_node(char *path)
+{
+	struct dirtree *dt;
+	char *name;
+
+	// Find last chunk of name.
+	
+	for (;;) {
+		name = strrchr(path, '/');
+
+		if (!name) name = path;
+		else {
+			if (*(name+1)) name++;
+			else {
+				*name=0;
+				continue;
+			}
+		}
+		break;
+	}
+
+   	dt = xzalloc(sizeof(struct dirtree)+strlen(name)+1);
+	xstat(path, &(dt->st));
+	strcpy(dt->name, name);
+
+	return dt;
+}
+
+// Given a directory (in a writeable PATH_MAX buffer), recursively read in a
+// directory tree.
+
+struct dirtree *read_dirtree(char *path)
+{
+	struct dirtree *dt = NULL, **ddt = &dt;
+	DIR *dir;
+	int len = strlen(path);
+
+	if (!(dir = opendir(path))) perror_msg("No %s", path);
+
+	for (;;) {
+		struct dirent *entry = readdir(dir);
+		if (!entry) break;
+
+		// Skip "." and ".."
+		if (entry->d_name[0]=='.') {
+			if (!entry->d_name[1]) continue;
+			if (entry->d_name[1]=='.' && !entry->d_name[2]) continue;
+		}
+
+		snprintf(path+len, sizeof(toybuf)-len, "/%s", entry->d_name);
+		*ddt = read_dirtree_node(path);
+		if (entry->d_type == DT_DIR) (*ddt)->child = read_dirtree(path);
+		ddt = &((*ddt)->next);
+		path[len]=0;
+	}
+
+	return dt;
+}
--- a/lib/lib.h	Sat Feb 03 14:10:00 2007 -0500
+++ b/lib/lib.h	Sat Feb 03 14:11:26 2007 -0500
@@ -21,6 +21,13 @@
 	char *arg;
 };
 
+struct dirtree {
+	struct dirtree *next;
+	struct dirtree *child;
+	struct stat st;
+	char name[];
+};
+
 // args.c
 void get_optflags(void);
 
@@ -52,6 +59,7 @@
 void xreadall(int fd, void *buf, size_t len);
 void xwrite(int fd, void *buf, size_t len);
 char *xgetcwd(void);
+void xstat(char *path, struct stat *st);
 char *xabspath(char *path);
 struct string_list *find_in_path(char *path, char *filename);
 void utoa_to_buf(unsigned n, char *buf, unsigned buflen);
@@ -59,6 +67,8 @@
 char *utoa(unsigned n);
 char *itoa(int n);
 off_t fdlength(int fd);
+struct dirtree *read_dirtree_node(char *path);
+struct dirtree *read_dirtree(char *path);
 
 // getmountlist.c
 struct mtab_list {