简单的glob在unix系统上的c++

Simple glob in C++ on unix system?

本文关键字:c++ 系统 glob 简单 unix      更新时间:2023-10-16

我想检索vector<string>中遵循此模式的所有匹配路径:

"/some/path/img*.png"

我该怎么做呢?

我有我的要点。我在glob周围创建了一个stl包装器,以便它返回字符串的向量,并负责释放glob结果。不是很有效,但这段代码更容易读,有些人会说更容易使用。

#include <glob.h> // glob(), globfree()
#include <string.h> // memset()
#include <vector>
#include <stdexcept>
#include <string>
#include <sstream>
std::vector<std::string> glob(const std::string& pattern) {
    using namespace std;
    // glob struct resides on the stack
    glob_t glob_result;
    memset(&glob_result, 0, sizeof(glob_result));
    // do the glob operation
    int return_value = glob(pattern.c_str(), GLOB_TILDE, NULL, &glob_result);
    if(return_value != 0) {
        globfree(&glob_result);
        stringstream ss;
        ss << "glob() failed with return_value " << return_value << endl;
        throw std::runtime_error(ss.str());
    }
    // collect all the filenames into a std::list<std::string>
    vector<string> filenames;
    for(size_t i = 0; i < glob_result.gl_pathc; ++i) {
        filenames.push_back(string(glob_result.gl_pathv[i]));
    }
    // cleanup
    globfree(&glob_result);
    // done
    return filenames;
}

可以使用glob() POSIX库函数

我为Windows编写了一个简单的glob库&Linux(可能也可以在其他*nix上工作)前一段时间当我无聊的时候,请随意使用它。

使用例子:

#include <iostream>
#include "glob.h"
int main(int argc, char **argv) {
  glob::Glob glob(argv[1]);
  while (glob) {
    std::cout << glob.GetFileName() << std::endl;
    glob.Next();
  }
}

对于c++ 17标准的新代码,std::filesystem存在,它可以通过std::filesystem::directory_iterator和递归版本实现这一点。您必须手动实现模式匹配。例如,c++ 11正则表达式库。这将被移植到任何支持c++ 17的平台。

std::filesystem::path folder("/some/path/");
if(!std::filesystem::is_directory(folder))
{
    throw std::runtime_error(folder.string() + " is not a folder");
}
std::vector<std::string> file_list;
for (const auto& entry : std::filesystem::directory_iterator(folder))
{
    const auto full_name = entry.path().string();
    if (entry.is_regular_file())
    {
       const auto base_name = entry.path().filename().string();
       /* Match the file, probably std::regex_match.. */
       if(match)
            file_list.push_back(full_name);
    }
}
return file_list;

在boost中也实现了一个类似的API,用于非c++ 17情况。std::string::compare()可能足以找到匹配,包括多个调用,lenpos参数只匹配子字符串。

我在Centos6上尝试了上面的解决方案,我发现我需要更改:

int ret = glob(pat.c_str(), 0, globerr, &glob_result);

(其中"globerr"是一个错误处理函数)

没有明确的0,我得到"GLOB_NOSPACE"错误。