Linux下使用C++遍历文件夹 遍历目录

这个经常用到 保存一下

#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\n", path);
        return;
    }

    if(!(d = opendir(path))) {
        //printf("opendir[%s] error: %m\n", 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\n",path, dp->d_name);
            char tmp[1024];
            sprintf(tmp,"%s/%s",path, dp->d_name);
            dst[tmp]=tmp;
        } else {
            //printf("%s/\n", 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]\n", argv[0]);
        printf("use DEFAULT option: %s .\n", argv[0]);
        printf("-------------------------------------------\n");
        path = "./";
    } else {
        path = argv[1];
    }

    map<string,string> dst;
    trave_dir(path,dst);
    for(auto cur:dst)printf("%s\n",cur.first.c_str());
    return 0;
}

 

posted on 2021-03-12 11:33  弘道者  阅读(1361)  评论(0编辑  收藏  举报