/* dired.c -- Playing with stats of files -- Given as command line parameter a file name, we print out its name, and, if it is a directory, we do the same recursively for all its elements. */ #include #include #include #include #include #include #include extern int errno; // It returns 1 iff path denotes a directory. int isDir(const char *path) { struct stat buffer; if (stat(path, &buffer) < 0){ fprintf(stderr, "stat: %s\n", strerror(errno)); return 0; }; if(S_ISDIR(buffer.st_mode)) return 1; else return 0; } // If the file denoted by pathname is a directory, // print out information about its descendants // one per line, indenting n+4 spaces. void print_descendants(const char *pathname, int n) { if (isDir(pathname)) { DIR *d; struct dirent *p; char path[512]; if ((d = opendir(pathname)) == NULL){ fprintf(stderr, "opendir %s %s\n", path, strerror(errno)); return; } p = readdir(d); // skip . p = readdir(d); // skip .. n = n+4; while ((p = readdir(d)) != NULL) { int k; for (k=0; kd_name); strcpy(path, pathname); strcat(path, "/"); strcat(path, p->d_name); print_descendants(path, n); } closedir(d); } } int main(int argc, char *argv[]) { if (argc != 2) { printf("usage: %s dirname\n", argv[0]); exit(0); } printf("%s\n", argv[1]); print_descendants(argv[1], 0); return 0; }