我可以使用掩码通过 Boost 迭代目录中的文件吗?
我想迭代目录中与 somefiles*.txt
等内容匹配的所有文件。
boost::filesystem
是否有内置的东西可以做到这一点,或者我是否需要针对每个 leaf()
的正则表达式或其他东西?
I want to iterate over all files in a directory matching something like somefiles*.txt
.
Does boost::filesystem
have something built in to do that, or do I need a regex or something against each leaf()
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
我相信directory_iterators只会提供目录中的所有文件。 您可以根据需要过滤它们。
I believe the directory_iterators will only provide all files in a directory. It up to you to filter them as necessary.
即使当我使用
i->path().extension()
而不是leaf()
时,接受的答案也无法为我编译。 对我有用的是此网站中的示例。 这是修改后的代码,用于应用过滤器:我使用的是 Boost 版本:1.53.0。
为什么我们不都只使用
glob()
和一些正则表达式超出了我的范围。The accepted answer did not compile for me even when I used
i->path().extension()
instead ofleaf()
. What did work for me was an example from this website. Here's the code, modified, to apply a filter:I'm using Boost version: 1.53.0.
Why we don't all just use
glob()
and some regex is beyond me.正如 Julien-L 的文章
QDir
的末尾所提到的,正是您想要的想要。https://qt-project.org/doc/ qt-5.0/qtcore/qdir.html#QDir-3
As mentioned at the end of Julien-L's post
QDir
is exactly what you want.https://qt-project.org/doc/qt-5.0/qtcore/qdir.html#QDir-3
我之前一直在寻找解决方案,我认为我的解决方案是最简单的
那么你可以这样做
I was looking for a solution to this earlier and I think my solution is the simplest
Then you can do
编辑:如注释中所述,下面的代码对于 v3 之前的
boost::filesystem
版本有效。 对于v3,请参考评论中的建议。boost::filesystem
没有通配符搜索,你必须自己过滤文件。这是一个使用
boost::filesystem
的directory_iterator
提取目录内容并使用boost::regex
进行过滤的代码示例:(如果您正在寻找具有内置目录过滤功能的即用类,请查看 Qt 的
QDir
。)EDIT: As noted in the comments, the code below is valid for versions of
boost::filesystem
prior to v3. For v3, refer to the suggestions in the comments.boost::filesystem
does not have wildcard search, you have to filter files yourself.This is a code sample extracting the content of a directory with a
boost::filesystem
'sdirectory_iterator
and filtering it withboost::regex
:(If you are looking for a ready-to-use class with builtin directory filtering, have a look at Qt's
QDir
.)有一个
Boost范围适配器
方式:There is a
Boost Range Adaptors
way:我的解决方案本质上与 Julien-L 相同,但封装在包含文件中,使用起来更好。 使用 boost::filesystem v3 实现。 我猜想类似的东西不会直接包含在 boost::filesystem 中,因为它会引入对 boost::regex 的依赖。
或者使用 FilteredRecursiveDirectoryIterator 进行递归子目录搜索:
FilteredDirectoryIterator.h
My solution is essentially the same as Julien-L, but encapsulated in the include file it is nicer to use. Implemented using boost::filesystem v3. I guess that something like that is not included in the boost::filesystem directly because it would introduce dependency on boost::regex.
alternatively use FilteredRecursiveDirectoryIterator for recursive sub directories search:
FilteredDirectoryIterator.h