ubuntu遍历文件夹

/*
    函数名称:scanDir
    函数作用:遍历文件夹内容
    输入参数:const char* dir ,输入文件夹
    输出参数:vector<string>& 输出内容
    输入参数:int depth 遍历深度
    输入参数:bool bDirOrFile 输出是文件还是文件夹,true表示将文件夹也输出路径也输出,false表示只输出文件路径
    返回值:无
*/

void scanDir(const char *dir,std::vector<std::string>& arrJsonPath, int depth, bool bDirOrFile)
{
    DIR *dp;                           // 定义子目录流指针  
    struct dirent *entry;         // 定义dirent结构指针保存后续目录  
    struct stat statbuf;           // 定义statbuf结构保存文件属性  
    if((dp = opendir(dir)) == NULL) // 打开目录,获取子目录流指针,判断操作是否成功  
    {  
         puts("can't open dir.");  
         return;  
    }  
    //chdir (dir);                                             // 切换到指定目录  
    while((entry = readdir(dp)) != NULL)  
    {  
         lstat(entry->d_name, &statbuf);                      // 获取下一级成员属性  
         if(S_IFDIR &statbuf.st_mode)                         // 判断下一级成员是否是目录  
         {  
              //过滤点
              if (strcmp(".", entry->d_name) == 0 || strcmp("..", entry->d_name) == 0)  
                  continue; 
              std::string strFilePath = dir;                   //合并文件路径
              strFilePath += "/";
              strFilePath += entry->d_name;
              if(depth > 1)                                    //判断深度是否继续
                  scanDir(strFilePath.c_str(), arrJsonPath, depth-1, bDirOrFile);              // 递归调用自身,扫描下一级目录,但是我们只遍历当前目录下的所有json文件
              if(bDirOrFile)
              {
                  arrJsonPath.push_back(entry->d_name);
              }
         }  
         else  
         {
              //输出文件路径
              std::string strFilePath = dir;
              strFilePath += "/";
              strFilePath += entry->d_name;
              arrJsonPath.push_back(strFilePath);
         }
    }  
    //chdir("..");                                                  // 回到上级目录  
    closedir(dp);                                                 // 关闭子目录流
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

telllong

你的鼓励是我创作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值