如何在目录及其子文件夹中构建文件名字符串向量?

How to build a vector of strings of filenames in a directory and its subfolders?

本文关键字:构建 文件名 字符串 向量 文件夹      更新时间:2023-10-16

我目前正在使用以下代码:

std::vector<std::string> paths;    
std::string path = "Assets/";
for (const auto& entry : std::filesystem::directory_iterator(path)) {
paths.push_back(entry.path().string());
}

但是,它会忽略Assets/文件夹中的子文件夹。如何让它跟踪子文件夹中的所有文件?

例如。假设Assets/目录如下所示:

Assets/
---image01.png
---image02.png
---somefile.txt
---subfolder/
------example.png
---anotherfolder/
------anotherfile.txt

我希望矢量看起来像这样:

Assets/image01.png
Assets/image02.png
Assets/somefile.txt
Assets/subfolder/example.png
Assets/anotherfolder/anotherfile.txt

您需要使用std::recursive_directory_iterator来获取嵌套目录的路径:

for (const auto& entry : std::filesystem::recursive_directory_iterator(path)) {
paths.push_back(entry.path().string());
}

此外,您可以直接存储它们,而不是将path存储为strings,如下所示:

std::vector<std::filesystem::path> paths;    

如果需要,您可以稍后将它们转换为string,但您也可以对它们执行其他操作。