20

在 Windows 中是否有一种流畅的方式在 C 或 C++ 中进行 glob?

例如,myprogram.exe *.txt 向我的程序发送一个 ARGV 列表,其中包含...ARGV[1]= *.txt

我希望能够有一个函数(我们称之为 readglob),它接受一个字符串并返回一个字符串向量,每个字符串都包含一个文件名。

这样,如果我的a.txt b.txt c.txt目录中有文件并且 readglob 得到一个参数*.txt,它会返回上面的文件列表。

//Prototype of this hypothetical function.
vector<string> readglob(string);

这样的存在吗?

4

5 回答 5

27

setargv.obj(or wsetargv.obj) 和 argv[] 的链接将为您提供类似于 Unix shell 的操作方式:

不过,我不能保证它做得有多好。

于 2009-08-13T01:01:04.477 回答
4

这是非常特定于 Windows 的。我不知道您如何将其编写为跨平台。但我已经在 Windows 程序中使用了它,它对我来说效果很好。

// Change to the specified working directory
string path;
cout << "Enter the path to report: ";
cin >> path;
_chdir(path.c_str());

// Get the file description
string desc;
cout << "Enter the file description: ";
cin >> desc;

// List the files in the directory
intptr_t file;
_finddata_t filedata;
file = _findfirst(desc.c_str(),&filedata);
if (file != -1)
{
  do
  {
    cout << filedata.name << endl;
    // Or put the file name in a vector here
  } while (_findnext(file,&filedata) == 0);
}
else
{
  cout << "No described files found" << endl;
}
_findclose(file);
于 2009-08-13T00:56:04.177 回答
2

曾经讨论过在 Boost::filesystem 中使用它,但为了使用 boost::regex 而放弃了它。

对于 win32 特定(MFC),您可以使用CFileFind

于 2009-08-13T00:47:45.310 回答
1

现在可能有更好的方法,但是上次我不得不处理这个问题时,我最终将Henry Spencer 的正则表达式库静态链接到我的程序中(他的库是 BSD 许可的),然后我制作了一个包装类来转换用户的将 glob 表达式转换为正则表达式以提供给正则表达式代码。如果您愿意,可以在此处查看/获取包装类。

一旦你有了这些部分,最后要做的就是读取目录,并将每个条目名称传递给匹配函数,看看它是否与表达式匹配。匹配的文件名,您添加到您的向量中;那些你不丢弃的。使用 DOS _findfirst() 和 _findnext() 函数读取目录相当简单,但如果你想要一个更好的 C++ 接口,我也有一个可移植的包装类......

于 2009-08-13T00:54:07.137 回答
0

呃。大约 15 年前,我不得不在 ANSI C 中实现类似的东西。我猜是从 ANSI opendir/readdir 例程开始的。Glob 并不完全是 RegEx,因此您必须实现自己的过滤。

于 2009-08-13T00:47:33.280 回答