C++搜索所有盘指定名称文件最快的方法
时间: 2023-11-29 08:04:20 浏览: 34
可以使用递归函数来搜索所有盘指定名称文件,以下是一个示例代码:
```c++
#include <iostream>
#include <string>
#include <filesystem>
namespace fs = std::filesystem;
void search_files(const fs::path& path, const std::string& target_file_name)
{
for (const auto& entry : fs::directory_iterator(path))
{
if (entry.is_directory())
{
search_files(entry.path(), target_file_name);
}
else if (entry.is_regular_file() && entry.path().filename() == target_file_name)
{
std::cout << "Found: " << entry.path() << std::endl;
}
}
}
int main()
{
const std::string target_file_name = "example.txt";
for (char drive_letter = 'A'; drive_letter <= 'Z'; ++drive_letter)
{
const fs::path drive_path(std::string(1, drive_letter) + ":\\");
if (fs::exists(drive_path))
{
search_files(drive_path, target_file_name);
}
}
return 0;
}
```
该代码使用了 C++17 中的文件系统库 `std::filesystem`,可以遍历指定路径下的所有文件和子目录,并且支持跨平台。在 `main` 函数中,该程序会搜索所有盘符,并使用 `search_files` 函数来搜索指定名称的文件。如果找到目标文件,就会输出文件的路径。