如何获取在给定文件夹中具有特定扩展名的文件列表 [英] How to get list of files with a specific extension in a given folder

查看:229
本文介绍了如何获取在给定文件夹中具有特定扩展名的文件列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能很简单,很抱歉提前:)

This is likely very simple, sorry in advance :)

我想获取在给定文件夹中具有特定扩展名的所有文件的文件名递归地,它的子文件夹)。也就是说,文件名(和扩展名),而不是完整的文件路径。这在Python这样的语言中是非常简单的,但我不熟悉C ++中的这种结构。如何做?

I want to get the file names of all files that have a specific extension in a given folder (and recursively, its subfolders). That is, the file name (and extension), not the full file path. This is incredibly simple in languages like Python, but I'm not familiar with the constructs for this in C++. How can it be done?

推荐答案

#define BOOST_FILESYSTEM_VERSION 3
#define BOOST_FILESYSTEM_NO_DEPRECATED 
#include <boost/filesystem.hpp>

namespace fs = ::boost::filesystem;

// return the filenames of all files that have the specified extension
// in the specified directory and all subdirectories
void get_all(const fs::path& root, const string& ext, vector<fs::path>& ret)
{
    if(!fs::exists(root) || !fs::is_directory(root)) return;

    fs::recursive_directory_iterator it(root);
    fs::recursive_directory_iterator endit;

    while(it != endit)
    {
        if(fs::is_regular_file(*it) && it->path().extension() == ext) ret.push_back(it->path().filename());
        ++it;

    }

}

这篇关于如何获取在给定文件夹中具有特定扩展名的文件列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆