以下是使用C++递归获取Home目录下的所有文件的示例代码:

#include <iostream>
#include <filesystem>

void recursiveListFiles(const std::filesystem::path& dirPath)
{
    for (const auto& entry : std::filesystem::directory_iterator(dirPath))
    {
        if (std::filesystem::is_directory(entry))
        {
            recursiveListFiles(entry.path()); // 递归调用自身处理子目录
        }
        else
        {
            std::cout << entry.path() << std::endl; // 输出文件路径
        }
    }
}

int main()
{
    const std::string homeDir = std::getenv("HOME"); // 获取Home目录路径
    const std::filesystem::path dirPath(homeDir);

    recursiveListFiles(dirPath);

    return 0;
}

这段代码使用了C++17中的std::filesystem库来处理文件和目录操作。recursiveListFiles函数递归地遍历指定目录下的所有文件和子目录,并输出文件的路径。主函数中,首先使用std::getenv获取Home目录的路径,然后将路径转换为std::filesystem::path对象,最后调用recursiveListFiles函数开始递归遍历


原文地址: https://www.cveoy.top/t/topic/iqh2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录