Use C++ to traverse all files in the specified folder, and get the file name and path and store it in JsonArray

Use C++ to traverse all the files in the specified folder, and get the file name and path and store it in JsonArray, and print it on the console. The format of each item in JsonArray is: file name, file path

The following code is given by ChatGPT:

The following is a code example that uses C++ to traverse all files in the specified folder and save the file name and path into JsonArray. In this example, we use the third-party library "nlohmann/json" to process data in Json format. You can include this library in your project, or use other JSON libraries.

#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;
}

In this code, we first define the folder path to traverse, and then define a JsonArray. In the loop of traversing folders, we first check whether the current entry is a file, if it is a file, store the file name and path in a Json object, and then add the Json object to JsonArray. Finally, we use the dump() method

Guess you like

Origin blog.csdn.net/qq_39085747/article/details/129497080