c / c ++中的平台无关的glob函数

时间:2013-05-17 01:22:12

标签: c++

有人知道一个c / cpp唯一的包可以与python glob函数等效吗?

基本上,我正在寻找类似的东西:

string startDirectory = "c:\foo\bar\*.txt"
vector<string> filename_list = getFilenameList(startDirectory)

注意:Python有一种非常可爱的方式:

glob(startDirectory)

注意:寻找一些适用于 Windows&amp; Linux ,并且 没有提升 - 只是标准的c ++,c。

1 个答案:

答案 0 :(得分:6)

这是具有相互矛盾要求的问题之一:

  • 没有图书馆

  • 便携式

诸如Boost之类的库的主要功能之一是允许您编写可移植代码。你的另一个选择就是编写一堆这样的代码:

#if defined _WIN32
#include <Windows.h>
std::vector<std::string> glob(const std::string &pattern)
{

}
#else
#include <glob.h>
std::vector<std::string> glob(const std::string &pattern)
{

}
#endif

你可能没有意识到可移植代码真的是多么痛苦。例如,如果用户在其文件名中放入Unicode字符,则std::ifstream基本上在Windows上被破坏。这就是我们喜欢图书馆的原因。

注意

C或C ++标准库中有 no 功能,允许您列出目录的内容。如果要进行通配,则拥有以使用特定于平台的代码。你唯一的选择就是你是编写自己的错误代码还是像其他人一样使用经过良好测试的库。