首先,标准 C++ 库不提供任何此类函数来列出目录中的文件。您可以使用 boost 库来完成这项工作。解决这个问题并不容易。您将不得不实施许多技术来完成这项工作。我可以给你所有可能的起点。
要将此代码移植到其他操作系统,您可能需要使用 # 预处理器指令添加特定于操作系统的代码。 Boost Liberay 已经是跨平台的。
首先你需要获取你的程序所在目录的当前路径:
为此,您可以使用以下 Windows 操作系统特定代码
#include <iostream>
#include <direct.h>
int main(){
char *path = NULL;
path = _getcwd(NULL, 0); // or _getcwd
if (path != NULL)
std::cout << path;
}
这里的路径变量包含当前目录的地址。您可以将此路径传递给下一个函数,该函数将进一步使用它为您列出文件和目录。要列出您可以使用的目录 Boost Liberaries http://www.boost.org/
接下来,您需要获取当前目录中存在的所有文件和文件夹。为此使用 Boost 库
使用来自 boost 的示例代码
http://www.boost.org/doc/libs/1_37_0/libs/filesystem/example/simple_ls.cpp
然后创建一个类并将接收到的地址和带有路径的文件名存储在其对象中。您可以将所有列出的地址存储在dir[1].str[size], dir[2].str[size],...等对象中。
现在再次将您收到的所有文件夹地址传递给增强功能并获取更多文件名。以上所有都需要多次通过。
您还可以获取特定文件扩展名的文件列表:
#define BOOST_FILESYSTEM_VERSION 3
#define BOOST_FILESYSTEM_NO_DEPRECATED
#include <boost/filesystem.hpp>
namespace fs = ::boost::filesystem;
// return the filenames of all files that have the specified extension
// in the specified directory and all subdirectories
void get_all(const fs::path& root, const string& ext, vector<fs::path>& ret)
{
if(!fs::exists(root) || !fs::is_directory(root)) return;
fs::recursive_directory_iterator it(root);
fs::recursive_directory_iterator endit;
while(it != endit)
{
if(fs::is_regular_file(*it) && it->path().extension() == ext) ret.push_back(it->path().filename());
++it;
}
}
最后将文件名与您要运行的文件名进行比较并执行。
这个问题也可以通过许多其他方法来解决,但我认为这是一个很好的开始,你可以随时改进你的代码。
参考资料:
- How to get list of files with a specific extension in a given folder
- http://www.boost.org/
-
How do I get a list of files in a directory in C++?
希望这会有所帮助。如果您需要任何进一步的帮助,请随时询问!