简单的glob在unix系统上的c++
Simple glob in C++ on unix system?
我想检索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()
可能足以找到匹配,包括多个调用,len
和pos
参数只匹配子字符串。
我在Centos6上尝试了上面的解决方案,我发现我需要更改:
int ret = glob(pat.c_str(), 0, globerr, &glob_result);
(其中"globerr"是一个错误处理函数)
没有明确的0,我得到"GLOB_NOSPACE"错误。
相关文章:
- C++,系统无法执行指定的程序
- 在UNIX系统中使用DIR查找文件的字节大小
- 错误处理.将系统错误代码映射到泛型
- 当系统的卷被修改时,如何修改WASAPI环回捕获卷
- 有什么好的方法可以让系统调用代理允许在单元测试中进行模拟
- 在C++游戏中与库存系统作斗争
- 文件系统:复制功能的速度秘诀是什么
- c++17文件系统::recursive_directory迭代器()在mac上没有给出这样的目录,但在windows上
- 在gtest.中使用fff.h模拟系统API
- 如何制作无限制照明系统
- 系统.将数组移交给c#中动态加载的c++DLL时发生AccessViolationException
- 如何传递多个 std::文件系统选项?
- 遍历顺序由 std::文件系统directory_iterator给出
- C++系统找不到指定的文件错误
- 系统参数信息A 与 SPI_GETMOUSE 返回 0
- libstdc++ 文件系统中未初始化的用法?
- 如何在ECS框架中更新组件数据和通知系统
- boost::文件系统::recursive_directory_iterator多线程安全
- 如果整个应用程序是虚拟映射的,为什么 new 会进行系统调用?
- SFML 碰撞永远不会在我的系统中注册