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

链接#

toml 完整版读取与写入#

toml读取#

toml写入#

目标:表嵌套子表数组的写入#

  • 比如:
  • 文件内容
Copy Highlighter-hljs
[NET_INTERFACE] bool = false bool_arr = [ false, false ] complex_arr = [ false, '456', 123 ] integer = 1234567890 integer_arr = [ 1, 0 ] str_arr = [ '1', '0' ] string = 'this is a string' [[NET_INTERFACE.fruit]] kilograms = 2 name = 'banana' [[NET_INTERFACE.fruit]] kilograms = 1 name = 'apple' [[NET_INTERFACE.fruit]] kilograms = 3 name = 'blueberry'

写文件 代码#

  • tableNodeInsert 函数定义
Copy Highlighter-hljs
/// @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)); }
  • 生成文件代码
Copy Highlighter-hljs
NetInterfaceConfigPropertyName propertyName; toml::table rootNode{}; 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); /// 下一是一个数组的写入 { /// 定义了水果信息 struct FruitInfo { /// 水果的名称 std::string m_name{""}; /// 水果的重量 int64_t m_kilograms{0}; }; /// <key-水果的名称,value-水果信息> using HashFruitInfo = std::unordered_map<std::string, FruitInfo>; HashFruitInfo fruitInfoHash{{"apple", {"apple", 1}}, {"banana", {"banana", 2}}, {"blueberry", {"blueberry", 3}}}; toml::array tmpArr; // for(auto& [key, value] : tmpArr) for (HashFruitInfo::iterator it = fruitInfoHash.begin(); it != fruitInfoHash.end(); ++ it) { toml::table tblTmp{}; tableNodeInsert<std::string>(tblTmp, "name", it->first); tableNodeInsert<int64_t>(tblTmp, "kilograms", it->second.m_kilograms); tmpArr.insert(tmpArr.begin(), tblTmp); } /// 将数组中的内容 - 关键代码 netInterfaceNode[propertyName.m_tableName].as_table()->insert_or_assign("fruit", tmpArr); } /// 使用流打开文件 std::ofstream tomlFile(std::string{"example.toml"}, std::ios::out | std::ios::trunc); if (tomlFile.is_open()) { // 使用 toml++ 的内置方法将 TOML 值写入文件 tomlFile << netInterfaceNode; tomlFile.close(); } else { /// TODO }

数组写入的关键代码#

Copy Highlighter-hljs
/// 将数组中的内容-关键代码 netInterfaceNode[propertyName.m_tableName].as_table()->insert_or_assign("fruit", tmpArr);
posted @   mohist  阅读(45)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2021-08-18 cmake之if
2021-08-18 cmake之譬判断cmake的版本
点击右上角即可分享
微信分享提示
CONTENTS