#include #include #include #include /* Maybe use perror() for readdir() setting errno? */ void tab(int num_spaces) { for ( ; num_spaces>0; num_spaces--) putchar(' '); } void walk_tree (char *path, int level) { DIR *pdir; struct dirent *entry; pdir = opendir(path); if (!pdir) { /* could check errno */ /* to see why */ fprintf(stderr, "Unable to open directory: %s\n", path); return; } fprintf(stderr, "Opened directory: %s\n", path); while (errno = 0, entry = readdir(pdir)) { tab(level); printf(" %s\n", entry->d_name); /* If entry is a directory, traverse it. */ } if (errno != 0) fprintf(stderr, "Unable to readdir: %s", path); if (closedir(pdir) == -1) fprintf(stderr, "Error closing directory: %s\n", path); return; } /* walk_tree() */ int main(int argc, char* argv[]) { char *path; /* We are either - called with exactly one argument, which is the pathname of a directory in which to start our traversal, or - called with no arguments, in which case we start with the current working directory. */ if (argc > 2) { fprintf(stderr, "Usage: %s [pathname]\n", argv[0]); exit(-1); } if (argc == 2) path = argv[1]; else path = "."; walk_tree(path, 0); } /* main() */