C++ 中的简单 glob在unix系统上?
我想检索 vector
中遵循此模式的所有匹配路径:
"/some/path/img*.png"
我怎样才能简单地做到这一点?
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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我的要点是这样的。我创建了一个围绕 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.
您可以使用
glob()
POSIX 库函数。You can use the
glob()
POSIX library function.我为 Windows 和 Windows 编写了一个简单的 glob 库。 Linux(可能也适用于其他*nixes),前一段时间我很无聊,随意使用它。
用法示例:
I wrote a simple glob library for Windows & Linux (probably works on other *nixes as well) a while ago when I was bored, feel free to use it as you like.
Example usage:
对于 C++17 标准的较新代码,存在
std::filesystem
,并且可以使用std::filesystem::directory_iterator
和递归版本来实现此目的。您必须手动实现模式匹配。例如,C++11 regex 库。这将可移植到任何支持 C++17 的平台。对于非 C++17 情况,boost 中也实现了类似的 API。
std::string::compare()
可能足以查找匹配项,包括多次调用,并使用len
和pos
参数来匹配 sub -仅限字符串。For newer code to the C++17 standard,
std::filesystem
exists and it can achieve this withstd::filesystem::directory_iterator
and the recursive version. You will have to manually implement the pattern matching. For instance, the C++11 regex library. This will be portable to any platform with C++17 support.A similar API is also implemented in boost for non-C++17 cases.
std::string::compare()
might be sufficient to find a match, including multiple calls, withlen
andpos
arguments to match sub-strings only.我已经在 Centos6 上尝试了上面的解决方案,我发现我需要更改:(
其中“globerr”是一个错误处理函数)
如果没有显式的 0,我会收到“GLOB_NOSPACE”错误。
I've tried the solutions above on Centos6, and I found out that I needed to change:
(where "globerr" is an error handling function)
Without the explicit 0, I got "GLOB_NOSPACE" error.