我想检索 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/