• 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
    ", 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;
    }
  • 相关阅读:
    模块和包
    mysql视图、存储过程等
    mysql 索引
    sql语句
    HTTP协议
    Django中的form组件
    数据结构
    一些常用函数
    C/C++中tag和type
    什么是compile-time-constant
  • 原文地址:https://www.cnblogs.com/yuandaozhe/p/14522862.html
Copyright © 2020-2023  润新知