filesystem::recursive_directory_iterator 举例
时间: 2024-02-04 11:04:32
浏览: 47
`filesystem::recursive_directory_iterator` 是 C++17 中的一个标准库类,用于遍历指定目录下的所有文件和子目录。以下是一个简单的例子:
```c++
#include <iostream>
#include <filesystem>
int main() {
std::filesystem::path path_to_dir = "/path/to/directory";
for (const [auto](https://geek.csdn.net/educolumn/0ed23d107a440608894f63cac98e73fb?spm=1055.2569.3001.10083)& entry : std::filesystem::recursive_directory_iterator(path_to_dir)) {
if (entry.is_directory()) {
std::cout << "Directory: " << entry.path().[string](https://geek.csdn.net/edu/8802d631b97a4a6af1f4d0bbf8527465?dp_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6NDQ0MDg2MiwiZXhwIjoxNzA3MzcxOTM4LCJpYXQiOjE3MDY3NjcxMzgsInVzZXJuYW1lIjoid2VpeGluXzY4NjQ1NjQ1In0.RrTYEnMNYPC7AQdoij4SBb0kKEgHoyvF-bZOG2eGQvc&spm=1055.2569.3001.10083)() << std::endl;
} else if (entry.is_regular_file()) {
std::cout << "File: " << entry.path().[string](https://geek.csdn.net/edu/8802d631b97a4a6af1f4d0bbf8527465?dp_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6NDQ0MDg2MiwiZXhwIjoxNzA3MzcxOTM4LCJpYXQiOjE3MDY3NjcxMzgsInVzZXJuYW1lIjoid2VpeGluXzY4NjQ1NjQ1In0.RrTYEnMNYPC7AQdoij4SBb0kKEgHoyvF-bZOG2eGQvc&spm=1055.2569.3001.10083)() << std::endl;
return 0;
上面的[代码](https://geek.csdn.net/educolumn/1572ef9b473b4e00f6b2bf6d428b7c27?spm=1055.2569.3001.10083)会遍历 `/path/to/directory` 目录下的所有文件和子目录,并打印出每个文件和子目录的路径。`is_directory()` 和 `is_regular_file()` [函数](https://geek.csdn.net/educolumn/ba94496e6cfa8630df5d047358ad9719?dp_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6NDQ0MDg2MiwiZXhwIjoxNzA3MzcxOTM4LCJpYXQiOjE3MDY3NjcxMzgsInVzZXJuYW1lIjoid2VpeGluXzY4NjQ1NjQ1In0.RrTYEnMNYPC7AQdoij4SBb0kKEgHoyvF-bZOG2eGQvc&spm=1055.2569.3001.10083)用于判断当前遍历到的是不是文件夹或文件。