C++ boost库 遍历读取文件夹文件

本文介绍了一个使用Boost.FileSystem库实现的C++程序,该程序能够递归地遍历指定目录下的所有子目录及文件,并筛选出所有的.jpg图片文件。此外,还提供了一个简单的单层目录读取函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem.hpp>

namespace fs = boost::filesystem;

//定义函数recursion,递归遍历全部文件夹
void recursion(path src_path)
{
    fs::directory_iterator end;             //迭代器的终点

    for (fs::directory_iterator dir(src_path); dir!=end; dir++)
    {
    //if (dir->path().extension() != ".jpg")
            //continue;
    string fn = dir->path().string();
    //cout << "file path:" << fn << endl;
    if (dir->path().extension() == ".jpg") {

        outf << "路径包含jpg名字:" << fn << endl;
        
    }
        if (fs::is_directory(*dir)) 
        recursion(*dir); //检查路径是否与目录对应(是文件夹则递归)
    }
}

//读取单层文件夹

void readfolder(string folderdir) {
    
    DIR * dir;
    struct dirent * ptr;
    string x,dirPath;
    dir = opendir((char *)folderdir.c_str()); //打开一个目录

    while((ptr = readdir(dir)) != NULL) //循环读取目录数据
    {
        x=ptr->d_name;
        if (x.length() < 5) {
          continue;
        }
        dirPath = folderdir + "/" + x;
        cout << "dirPath:" << dirPath << endl;


    }
    closedir(dir);//关闭目录指针

}

int main(int argc, char* argv[]) {
  //readtxtfile();
  //readfolder("./xinshangpic");
  recursion("/data/project/xing/xinshang_dataset/xinshang_img/");

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值