C++ C+中的简单glob+;在unix系统上?
我想在C++ C+中的简单glob+;在unix系统上?,c++,unix,glob,C++,Unix,Glob,我想在向量中检索遵循此模式的所有匹配路径: 我怎样才能简单地做到这一点呢?您可以使用POSIX库函数。Mostlikely是最接近的。这很有可能在C++11中得到支持。我的要点中有这一点。我围绕glob创建了一个stl包装器,以便它返回字符串的向量,并负责释放glob结果。虽然效率不高,但这段代码可读性更强,有些人会说更容易使用 #include <glob.h> // glob(), globfree() #include <string.h> // memset()
向量中检索遵循此模式的所有匹配路径
:
我怎样才能简单地做到这一点呢?您可以使用POSIX库函数。Mostlikely是最接近的。这很有可能在C++11中得到支持。我的要点中有这一点。我围绕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(),globfree()
#include//memset()
#包括
#包括
#包括
#包括
标准::矢量全局(常量标准::字符串和模式){
使用名称空间std;
//全局结构驻留在堆栈上
glob_t glob_结果;
memset(&glob_result,0,sizeof(glob_result));
//执行全局操作
int return_value=glob(pattern.c_str(),glob_TILDE,NULL,&glob_result);
if(返回_值!=0){
globfree(&glob_结果);
细流ss;
ss不久前,我为Windows和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();
}
}
#包括
#包括“glob.h”
int main(int argc,字符**argv){
glob::globglob(argv[1]);
while(全球){
std::cout我在Centos6上尝试了上述解决方案,发现我需要改变:
int ret = glob(pat.c_str(), 0, globerr, &glob_result);
(其中“globerr”是一个错误处理函数)
如果没有显式的0,我得到了“GLOB_NOSPACE”错误。GLOB()是POSIX而不是C99,并且它确实存在于任何与POSIX兼容的现代UNIX发行版上。是的,没错。我真正想说的是,这是一个C风格的函数(生成char**
而不是std::vector
等等)但是,在C++编程中使用它仍然是正确的函数。编写一个“C++风格”接口的包装器也相当容易。我认为OP想使字符串向量化,从我能看到的GLUB(3)中提取。函数实际上是在文件系统中查找的…是否有任何库函数不访问文件系统--我也需要它。这不会检查任何错误,如果任何向量操作都会泄漏内存throws@wakjah我还注意到缺少错误检查(big no no),所以我刚刚编辑了代码并保存了它。
int ret = glob(pat.c_str(), 0, globerr, &glob_result);