int print_dirs(const char *path, int recursive) { struct dirent *direntp = NULL; DIR *dirp = NULL; size_t path_len; if (!path) return -1; path_len = strlen(path); if (!path || !path_len || (path_len > _POSIX_PATH_MAX)) return -1; dirp = opendir(path); if (dirp == NULL) return -1; while ((direntp = readdir(dirp)) != NULL) { struct stat fstat; char full_name[_POSIX_PATH_MAX + 1]; if ((path_len + strlen(direntp->d_name) + 1) > _POSIX_PATH_MAX) continue; strcpy(full_name, path); if (full_name[path_len - 1] != '/') strcat(full_name, "/"); strcat(full_name, direntp->d_name); if ((strcmp(direntp->d_name, ".") == 0) || (strcmp(direntp->d_name, "..") == 0)) continue; if (stat(full_name, &fstat) < 0) continue; if (S_ISDIR(fstat.st_mode)) { printf("%s\n", full_name); if (recursive) print_dirs(full_name, 1); } } (void)closedir(dirp); return 0; } int main(int argc, const char* argv[]) { if (argc < 2) return -1; print_dirs(argv[1], 1); return 0; }
source share