关于c++使用toml plusplus(俗称toml++)的使用

链接

toml 完整版读取与写入

toml读取

toml写入

  • 一个范例,一个开胃菜

toml文件

  • 待生成的目标文件内容为
[NET_INTERFACE]
bool = false
integer = 1234567890
string = 'this is a string'

关键代码

  • toml.h头文件的代码
/// ----------------------------------------------------
/// @file toml.h
/// @author oct (oct@oct.com)
/// @brief toml中常用的一些函数的转换
/// @version 0.1
/// @date 2024-08-12
/// 
/// @copyright Copyright (c) 2024
/// 
/// ----------------------------------------------------

#ifndef TOML_H_
#define TOML_H_
#include <string>
#include <toml.hpp>

namespace oct 
{
    /// @brief 插入非string节点
    /// @param whichTable -哪个表
    /// @param key - 插入的数据值
    /// @param value -值
    template<typename T>
    static void tableNodeInsert(toml::table& whichTable, const std::string& key, const T& value)
    {
        whichTable.insert_or_assign(key, toml::value<T>(value));
    }
}

#endif ///! TOML_H_

写文件关键代码

/// 定义了表的一些键的名称
NetInterfaceConfigPropertyName propertyName;

toml::table rootNode{};
/// 参数1-哪个表,参数2-节点的key, 参数3-将要插入的值
tableNodeInsert<std::string>(rootNode, "string", "this is a string");
tableNodeInsert<bool>(rootNode, "bool", false);
tableNodeInsert<int64_t>(rootNode, "integer", 1234567890);

toml::table netInterfaceNode{};
/// 创建[NET_INTERFACE]
netInterfaceNode.insert_or_assign(propertyName.m_tableName, rootNode);

/// 使用流打开文件
std::globalToml{"EXAMPLE.toml"};
std::ofstream tomlFile(globalToml, std::ios::out | std::ios::trunc);
if (tomlFile.is_open())
{
	// 使用 toml++ 的内置方法将 TOML 值写入文件
	tomlFile << netInterfaceNode;
	tomlFile.close();
}
else
{
	std::cout << "failed to write file";
	return 2;
}
posted @ 2024-08-18 22:39  mohist  阅读(42)  评论(0编辑  收藏  举报