c++ - Unix系统上C++中的简单glob?

标签 c++ unix glob

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

"/some/path/img*.png"

我怎样才能简单地做到这一点?

最佳答案

我的要点是。我在 glob 周围创建了一个 STL 包装器,以便它返回字符串 vector 并负责释放 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;
}

关于c++ - Unix系统上C++中的简单glob?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8401777/

相关文章:

c++ - 检查顶点之间的平行边 : edge_range does not work with directed graph

c++ - 我应该仅使用构造函数来进行 C++ 中的变量初始化吗?

python - 如何检查是否已为 VIRTUALENVWRAPPER_PYTHON=/usr/bin/python 等安装了 virtualenvwrapper

linux - 如何编写一个shell脚本来添加两个数字?

python - 我不明白 Python 中的 'from'

c++ - 不同容器上的 std::stack 实现有什么实际区别?

c++ - 析构函数调用时访问冲突读取位置 0xfeeefe2

linux - 在 Linux 中,获取两个字符串之间的内容

regex - BASH glob/regex 范围的奇怪行为

perl - 如何使用 Perl glob 返回文件的绝对路径名?