Use C++ code to traverse all MP4 files and PNG files in the specified folder under ubuntu, get their file names and paths, and store them in the JsonArray container

This piece of code is given by ChatGPT:

#include <iostream>
#include <string>
#include <boost/filesystem.hpp> // 引入boost库中的文件系统功能
#include <jsoncpp/json/json.h> // 引入jsoncpp库

using namespace std;
namespace fs = boost::filesystem;

int main(int argc, char* argv[]) {
    if (argc < 2) {
        cerr << "Usage: " << argv[0] << " [directory path]" << endl;
        return 1;
    }

    // 获取指定目录的路径
    fs::path dir_path(argv[1]);
    if (!fs::is_directory(dir_path)) {
        cerr << dir_path << " is not a directory" << endl;
        return 1;
    }

    // 创建一个JsonArray容器
    Json::Value json_array(Json::arrayValue);

    // 遍历目录中的文件
    for (fs::directory_iterator itr(dir_path); itr != fs::directory_iterator(); ++itr) {
        if (fs::is_regular_file(itr->path())) { // 判断是否为普通文件
            fs::path file_path = itr->path(); // 获取文件路径
            string file_extension = file_path.extension().string(); // 获取文件扩展名

            if (file_extension == ".mp4" || file_extension == ".png") { // 判断是否为MP4或PNG文件
                // 创建一个JsonObject,包含文件名和路径信息
                Json::Value json_file(Json::objectValue);
                json_file["filename"] = file_path.filename().string();
                json_file["path"] = file_path.string();
                // 将JsonObject添加到JsonArray容器中
                json_array.append(json_file);
            }
        }
    }

    // 将JsonArray容器转化为Json字符串输出
    Json::StyledWriter writer;
    cout << writer.write(json_array) << endl;

    return 0;
}

Note that this code requires the boost library and the jsoncpp library to be installed in order to compile. You can install them on Ubuntu with the following commands:

sudo apt-get install libboost-all-dev libjsoncpp-dev

 When compiling, you need to link the boost and jsoncpp libraries. You can compile your code with:

g++ -o program_name program_name.cpp -lboost_system -lboost_filesystem -ljsoncpp

 

Guess you like

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