#include <stdio.h> #include <dirent.h> #include <sys/types.h> #include <sys/stat.h> #include <string> #include <string.h> using namespace std; void List(const char *path, int level) { struct dirent* ent = NULL; DIR *pDir; pDir = opendir(path); if (pDir == NULL) { //被当作目录,但是执行opendir后发现又不是目录,比如软链接就会发生这样的情况。 return; } while (NULL != (ent = readdir(pDir))) { if (ent->d_type == 8) { //file for (int i = 0; i < level; i++) { printf("-"); } printf("%s\n", ent->d_name); } else { if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) { continue; } //directory std::string _path(path); std::string _dirName(ent->d_name); std::string fullDirPath = _path + "/" + _dirName; for (int i = 0; i < level; i++) { printf(" "); } printf("%s/\n", ent->d_name); List(fullDirPath.c_str(), level + 1); } } } int main(int argc, char *argv[]) { List("/home/yangchao", 0); return 0; }