学堂 学堂 学堂公众号手机端

C++怎么读取文件夹中的所有文件

lewis 3年前 (2022-09-11) 阅读数 4 #技术

要在C++中读取文件夹中的所有文件,可以使用标准库中的<filesystem>头文件。下面是一个简单的示例代码,演示如何遍历文件夹中的所有文件:

#include <iostream>
#include <filesystem>

namespace fs = std::filesystem;

int main() {
    // 指定要遍历的文件夹路径
    fs::path folderPath = "path_to_folder";

    // 检查文件夹是否存在
    if (!fs::exists(folderPath) || !fs::is_directory(folderPath)) {
        std::cerr << "Folder does not exist." << std::endl;
        return 1;
    }

    // 遍历文件夹中的所有文件
    for (const auto& entry : fs::directory_iterator(folderPath)) {
        std::cout << entry.path().filename() << std::endl;
    }

    return 0;
}

在上面的代码中,首先指定要遍历的文件夹路径,然后使用fs::directory_iterator来遍历文件夹中的所有文件。对于每个文件,我们输出其文件名。

需要注意的是,以上代码需要C++17标准及以上版本的支持。如果你使用的是更早的C++标准,可能需要使用其他库或方法来实现相同的功能。


版权声明

本文仅代表作者观点,不代表博信信息网立场。

热门