这个经常用到 保存一下
#include <stdio.h> #include <string.h> #include <sys/types.h> #include <dirent.h> #include <sys/stat.h> #include <string> #include <map> using namespace std; static void trave_dir(char* path,map<string,string>& dst) { DIR *d = NULL; struct dirent *dp = NULL; struct stat st; char p[1024] = {0}; if(stat(path, &st) < 0 || !S_ISDIR(st.st_mode)) { //printf("invalid path: %s ", path); return; } if(!(d = opendir(path))) { //printf("opendir[%s] error: %m ", path); return; } while((dp = readdir(d)) != NULL) { if((!strncmp(dp->d_name, ".", 1)) || (!strncmp(dp->d_name, "..", 2))) continue; snprintf(p, sizeof(p) - 1, "%s/%s", path, dp->d_name); stat(p, &st); if(!S_ISDIR(st.st_mode)) { //printf("%s/%s ",path, dp->d_name); char tmp[1024]; sprintf(tmp,"%s/%s",path, dp->d_name); dst[tmp]=tmp; } else { //printf("%s/ ", dp->d_name); trave_dir(p,dst); } } closedir(d); return; } int main(int argc, char **argv) { char *path = NULL; if (argc != 2) { printf("Usage: %s [dir] ", argv[0]); printf("use DEFAULT option: %s . ", argv[0]); printf("------------------------------------------- "); path = "./"; } else { path = argv[1]; } map<string,string> dst; trave_dir(path,dst); for(auto cur:dst)printf("%s ",cur.first.c_str()); return 0; }