abcde5342376 发表于 2013-2-1 12:38:15

C/C++ 遍历linux目录下所有文件并已树的形式打印

#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) {//filefor (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;}//directorystd::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;}
页: [1]
查看完整版本: C/C++ 遍历linux目录下所有文件并已树的形式打印