在 C 中解析 YAML 文件

新手上路,请多包涵

我想要一个简单的教程来向我展示如何加载 yaml 文件并解析数据。 Expat 风格会很棒,但任何能够以某种形式实际向我展示数据的解决方案都会很有用。

到目前为止,我在 yaml-0.1.1 源代码中运行了多个测试 C 并且我得到一个错误,没有任何输出,或者在 run-emitter.c 案例中。它读入 yaml 文件并将其打印到 STDOUT ,它不会通过 libyaml 函数/结构生成文本。在出现错误的情况下,我不知道是因为文件错误还是我的构建不正确(我没有修改任何内容……)该文件是从 yaml.org 复制的

谁能指点我一个教程? (我用谷歌搜索了至少 30 分钟,阅读了任何看起来相关的内容)或具有良好教程或示例的库的名称。也许您可以告诉我哪个 libyaml 测试加载文件并对其进行处理,或者我为什么会出错。本文档不解释如何 使用 该文件——只解释如何加载它:

http://pyyaml.org/wiki/LibYAML#Documentation

原文由 user34537 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.5k
1 个回答

作为 yaml-cpplibyaml 的替代品,有 rapidyaml 。这是一个例子。

 #include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>

#include <ryml_std.hpp>
#include <ryml.hpp>

std::string get_file_contents(const char *filename)
{
    std::ifstream in(filename, std::ios::in | std::ios::binary);
    if (!in) {
        std::cerr << "could not open " << filename << std::endl;
        exit(1);
    }
    std::ostringstream contents;
    contents << in.rdbuf();
    return contents.str();
}

int main(int argc, char const *argv[])
{
    std::string contents = get_file_contents("config.yaml");
    ryml::Tree tree = ryml::parse_in_place(ryml::to_substr(contents));
    ryml::NodeRef foo = tree["foo"];
    for (ryml::NodeRef const& child : foo.children()) {
        std::cout << "key: " << child.key() << " val: " << child.val() << std::endl;
    }

    ryml::NodeRef array = tree["matrix"]["array"];
    for (ryml::NodeRef const& child : array.children()) {
        double val;
        child >> val;
        std::cout << "float val: " << std::setprecision (18) << val << std::endl;
    }
    return 0;
}

配置.yaml

 foo:
  bar: a
  barbar: b
  barbarbar: c

matrix:
  array:
    - 0.045533736417839546
    - 0.16564066086021373
    - 0.028658520327566304
    - 0.009133486414620372
    - -0.5801749091384203

更新

请注意,该项目递归地使用子模块,这就是为什么 GitHub 上的“下载 ZIP”选项不起作用的原因。使用 git

 git clone --recurse-submodules -j8 https://github.com/biojppm/rapidyaml.git

考虑到您在 第三方/rapidyaml 中克隆了 rapidyaml 这是一个最小的 cmake 配置。

CMakeLists.txt

 cmake_minimum_required(VERSION 3.14)

project(so_answer VERSION 0.0.1 LANGUAGES CXX)

set(CMAKE_CXX_STANDARD_REQUIRED ON)

add_subdirectory(thirdparty/rapidyaml)

add_executable(example example.cpp)
target_include_directories(example PRIVATE thirdparty/rapidyaml/src)
target_link_libraries(example ryml)

原文由 Mikolasan 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏