用C++遍历指定文件夹内的所有文件,并获取文件名和路径并存入JsonArray

用C++遍历指定文件夹内的所有文件,并获取文件名和路径并存入JsonArray,并打印在控制台,JsonArray中的每一项格式均为:文件名,文件路径

以下代码是由ChatGPT给出的:

以下是使用C++遍历指定文件夹内所有文件,并将文件名和路径存入JsonArray的代码示例。在这个例子中,我们使用第三方库"nlohmann/json"来处理Json格式的数据。你可以在你的项目中包含这个库,或者使用其他的JSON库。

#include <iostream>
#include <fstream>
#include <filesystem>
#include "nlohmann/json.hpp"

using json = nlohmann::json;
namespace fs = std::filesystem;

int main() {
    // 指定要遍历的文件夹路径
    std::string folder_path = "/path/to/folder";

    // 定义JsonArray
    json json_array = json::array();

    // 遍历文件夹
    for (const auto& entry : fs::directory_iterator(folder_path)) {
        // 如果entry是文件,则将文件名和路径加入JsonArray
        if (entry.is_regular_file()) {
            json file_info;
            file_info["file_name"] = entry.path().filename().string();
            file_info["file_path"] = entry.path().string();
            json_array.push_back(file_info);
        }
    }

    // 输出JsonArray
    std::cout << json_array.dump(4) << std::endl;

    return 0;
}

这段代码中,我们首先定义了要遍历的文件夹路径,然后定义了一个JsonArray。在遍历文件夹的循环中,我们首先检查当前entry是否是文件,如果是文件,则将文件名和路径存入一个Json对象中,然后将该Json对象加入JsonArray中。最后,我们使用dump()方法

猜你喜欢

转载自blog.csdn.net/qq_39085747/article/details/129497080