如何在路径中搜索具有特定模式的文件

时间:2013-12-23 18:07:06

标签: c++ boost filesystems

如果文件与模式匹配,我正在寻找一种在目录(及其子目录)中查找文件的方法。

我有这段代码:

 inline static void ScanForFiles(std::vector<string> &files,const path &inputPath,string filter="*.*",bool recursive=false)
 {
        typedef vector<boost::filesystem::path> vec;             // store paths,
        vec v;                                // so we can sort them later

        copy(directory_iterator(inputPath), directory_iterator(), back_inserter(v));
        for(int i=0; i<v.size(); i++)
        {
            if(IsDirectory(v[i]))
            {
                if(recursive)
                {
                    ScanForDirs(files,v[i],recursive);
                }
            }
            else
            {
                if(File::IsFile(v[i]))
                {
                    files.push_back(v[i].string());
                }
            }
        }
}

这是有效的,但它与pattenrs不匹配。例如,我想这样调用这个函数:

std::vector<string> files;
ScanForFiles(files,"c:\\myImages","*.jpg",true);

我得到了myimages及其所有子文件夹中所有jpeg图像的列表。

当前代码返回所有图像,并且没有模式匹配。

如何更改上述代码?

1 个答案:

答案 0 :(得分:0)

我想出了以下片段:

#include <iostream>
#include <string>
#include <boost/regex.hpp>

std::string escapeRegex(const std::string &str) {
  boost::regex esc("([\\^\\.\\$\\|\\(\\)\\[\\]\\*\\+\\?\\/\\\\])");                                                         
  std::string rep("\\\\\\1");
  return regex_replace(str, esc, rep, boost::match_default | boost::format_sed);
}

std::string wildcardToRegex(const std::string &pattern) {
  boost::regex esc("\\\\([\\*\\?])");
  std::string rep(".\\1");
  return regex_replace(escapeRegex(pattern), esc, rep, boost::match_default | boost::format_sed);
}

using namespace std;
using namespace boost;
int main(int argc, char **argv) {
  string pattern = "test/of regexes/*.jpg";
  cout << wildcardToRegex(pattern) << endl;
}

它主要基于this question。我希望这会有所帮助。