c++如何遍历文件夹所有文件

2024-03-26

c++中,可以使用标准库中的<filesystem>来遍历文件夹中的所有文件。下面是一个简单的示例代码:

#include <iostream>
#include <filesystem>

namespace fs = std::filesystem;

void listFiles(const std::string& path) {
    for (const auto& entry : fs::directory_iterator(path)) {
        if (fs::is_regular_file(entry.path())) {
            std::cout << entry.path() << std::endl;
        } else if (fs::is_directory(entry.path())) {
            listFiles(entry.path().string());
        }
    }
}

int main() {
    std::string path = "path_to_your_folder";
    listFiles(path);
    
    return 0;
}

在上面的示例中,listFiles函数接收一个文件夹路径作为参数,然后遍历该文件夹中的所有文件。如果遇到子文件夹,递归调用listFiles函数来遍历子文件夹中的文件。通过调用entry.path()可以获取当前文件或文件夹的路径信息。

《c++如何遍历文件夹所有文件.doc》

下载本文的Word格式文档,以方便收藏与打印。