提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
C++ 读取yaml文件中的列表项,并利用列表项中的数据进行复制
前言
主要用到的知识点**(注意:yaml-cpp/yaml.h需要自行导入**):
1,filesystem相关的库函数操作(copy、exists等)
2,列表项中的属性的读取
这里的案列流程如下:
1,读取test.yaml文件中的列表项并得到列表项中的属性path
2,根据列表项提供的路径path,将该path路径下的yaml文件复制到目标文件下
一、完整代码和注释
1.引入库
#include <iostream>
#include <fstream>
#include <yaml-cpp/yaml.h>
#include <filesystem>
using namespace std;
namespace fs = std::filesystem;
2.主要代码
void copyYAMLFiles(const std::string& sour_path, const std::string& dest_path) {
// 读取当前的 YAML 文件
YAML::Node config = YAML::LoadFile(sour_path);
// 从YAML文件中提取路径列表
if (!config["devices"] || !config["devices"].IsSequence()) {
std::cerr << "未在 YAML 文件中找到 'devices' 参数或参数不是列表。" << std::endl;
return;
}
// 遍历列表中的每个路径
for (const auto& node : config["devices"]) {
// 这里可以多设置几个必须用到的属性
if (!node["name"] || !node["path"]) {
std::cerr << "YAML 列表项中缺少 'name' 或 'path' 参数。" << std::endl;
continue;
}
std::string name = node["name"].as<std::string>();
fs::path sourcePath = node["path"].as<std::string>();
// 根据name进行判断,决定是否处理当前路径
if (name == "dev1") {
// 检查sourcePath是否存在
if (!fs::exists(sourcePath)) {
std::cerr << "源文件路径不存在:" << sourcePath << std::endl;
continue; // 如果路径不存在,跳过这个路径
}
// 获取文件名,并拼接到目标目录路径
fs::path destinationPath = fs::path(dest_path) / sourcePath.filename();
try {
// 复制文件到目标路径
fs::copy(sourcePath, destinationPath, fs::copy_options::overwrite_existing);
std::cout << "文件已成功复制到:" << destinationPath << std::endl;
} catch (const fs::filesystem_error& e) {
std::cerr << "文件复制失败:" << e.what() << std::endl;
}
}
}
}
int main() {
// 源 YAML 文件的路径
std::string sour_path = "test.yaml";
// 目标目录路径
std::string test_result = "./test_result";
// 执行文件复制操作
copyYAMLFiles(sour_path, test_result);
return 0;
}
二,代码演示结果
1,test.yaml内容
2,/test/test1.yaml
3,代码复制结果(/test_result/dev1.yaml)
。