我试图使用Boost库从C:/目录检索所有文件。
当输入是带有目录的文件路径(例如: C:\Windows)时,我可以检索所有文件,但是当指定的路径仅为C:**时,我会得到一个错误。我也尝试过使用C:**,但是从我的项目目录而不是从根目录提升搜索文件。
我还为C:\Windows添加了一个排除项,这个部分工作得很好。
那么如何从**C:**启动recursive_directory_iterator呢?
这是我的代码:
//string rootPath = boost::filesystem::current_path().root_directory().string();
string rootPath = "C:";
string exclusionPath = rootPath+"\\"+"Windows";
void myClass::getFile()
{
for (boost::filesystem::recursive_directory_iterator end, dir(rootPath); dir != end; ++dir)
{
string filePath = dir->path().string();
if (boost::filesystem::is_regular_file(*dir) && filePath.find(exclusionPath) == string::npos)
{
cout << filePath << endl;
}
}
}发布于 2021-07-20 19:47:06
如果使用的是c++17标准库,则可以利用标准文件系统库。它的工作方式类似于boost文件系统,这两个库的API非常相似。您必须将文件系统头包含在
#include <filesystem>通过调用以下命令,可以递归地遍历目录中的每个文件:
for (std::filesystem::directory_entry entry : std::filesystem::recursive_directory_iterator(rootPath))这将给您一个目录条目,它就像boost目录条目一样,包含一个路径。我能够用标准库复制您的示例代码,并得到了如下所示的工作示例:
#include <filesystem>
#include <string>
#include <iostream>
std::filesystem::path rootPath = "C:";
std::filesystem::path exclusionPath = rootPath / "Windows";
int main()
{
for (std::filesystem::directory_entry entry : std::filesystem::recursive_directory_iterator(rootPath))
{
std::string filePath = entry.path().string();
if (std::filesystem::is_regular_file(entry.path()) && filePath.find(exclusionPath.string()) == std::string::npos)
{
std::cout << filePath << std::endl;
}
}
}如您所见,我将用于以上路径的字符串转换为路径。这不是必要的,但最好是预先构造一个路径,因为否则您调用的每个函数都会用您放入的字符串构造一个新路径。路径奇怪地使用/运算符将两条路径附加在一起,例如在Windows上
std::filesystem::path exclusionPath = rootPath / "Windows";会给你C:\Windows。
https://stackoverflow.com/questions/68460077
复制相似问题