unix 系统上的 C++ 中的简单 glob? [英] Simple glob in C++ on unix system?
本文介绍了unix 系统上的 C++ 中的简单 glob?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在 vector
中检索遵循此模式的所有匹配路径:
I want to retrieve all the matching paths following this pattern in a vector<string>
:
"/some/path/img*.png"
我怎么能简单地做到这一点?
How can I simply do that ?
推荐答案
我的要点就是这个.我在 glob 周围创建了一个 stl 包装器,以便它返回字符串向量并处理释放 glob 结果.不是很有效,但这段代码更易读,有些人会说更容易使用.
I have that in my gist. I created a stl wrapper around glob so that it returns vector of string and take care of freeing glob result. Not exactly very efficient but this code is a little more readable and some would say easier to use.
#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;
}
这篇关于unix 系统上的 C++ 中的简单 glob?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文