C++模仿 ls 之类的命令
如何实现 ls "filename_[0-5][3-4]?" 这样的类?我想将结果存储在向量中。
目前我正在使用system(),它正在调用ls,但这在MS下不可移植。
谢谢, 阿曼.
How to implement the ls "filename_[0-5][3-4]?" like class? The result I would like to store in the vector.
Currently I am using system() which is calling ls, but this is not portable under MS.
thanks,
Arman.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
以下程序列出当前目录中名称与正则表达式
filename_[0-5][34]
匹配的文件:为简洁起见,我省略了
transform_if()
的定义。它不是标准函数,但应该很容易实现。The following program lists files in the current directory whose name matches the regular expression
filename_[0-5][34]
:I omitted the definition of
transform_if()
for brevity. It isn't a standard function but it should be straightforward to implement.您可以使用 boost::filesystem,它具有可移植的方式来检索目录中的文件。
然后,您可以使用 boost::regex 对照正则表达式检查文件,以仅保留与您的模式匹配的文件。
You can use boost::filesystem which has a portable way to retrieve files in a directory.
Then you can check the files against a regular expression with boost::regex for instance to only keep the ones that match your pattern.
升压解决方案是可移植的,但在 Windows 上并不是最佳的。原因是它调用
FindFirstFile("*.*")
并因此返回所有内容。考虑到通配模式,调用 FindFirstFile("filename_?*.*") 会更有效。您仍然必须过滤结果(使用例如 Boost::regex),但这会排除许多不可能匹配的文件。另外,使用任何一种方法都不要忘记在进行正则表达式匹配之前过滤掉目录。检查一个条目是否是一个目录是相当便宜的。
The boost solution is portable, but not optimal on Windows. The reason is that it calls
FindFirstFile("*.*")
and thus returns everything. Given the globbing pattern, it would be more efficient to callFindFirstFile("filename_?*.*")
. You'd still have to filter the results (using e.g. Boost::regex) but this would exclude many files that can't possibly match.Also, using either method don't forget to filter out directories before doing the regex matching. The check whether an entry is a directory is quite cheap.