How to read and write .ini files using boost library [duplicate]

社会主义新天地 提交于 2019-12-04 15:30:54

With Boost.PropertyTree you can read and update the tree, then write to a file (see load and save functions.

Have a look at How to access data in property tree. You can definitely add new property or update existing one. It mentiones that there's erase on container as well so you should be able to delete existing value. Example from boost (link above):

ptree pt;
pt.put("a.path.to.float.value", 3.14f);
// Overwrites the value
pt.put("a.path.to.float.value", 2.72f);
// Adds a second node with the new value.
pt.add("a.path.to.float.value", 3.14f);

I would assume you would then write updated tree into a file, either new one or overwrite existing one.

EDIT : For ini file it does specific checks.

The above example if you try to save to ini with ini_parser you get:

  1. ptree is too deep
  2. duplicate key

With that fixed here is an example code that writes ini file, I've updated a value of existing key then added a new key:

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>

void save(const std::string &filename)
{
   using boost::property_tree::ptree;

//   pt.put("a.path.to.float.value", 3.14f);
//   pt.put("a.path.to.float.value", 2.72f);
//   pt.add("a.path.to.float.value", 3.14f);

   ptree pt;
   pt.put("a.value", 3.14f);
   // Overwrites the value
   pt.put("a.value", 2.72f);
   // Adds a second node with the new value.
   pt.add("a.bvalue", 3.14f);

   write_ini( filename, pt );
}

int main()
{
    std::string f( "test.ini" );
    save( f );
}

the test.ini file:

[a]
value=2.72
bvalue=3.14

Feel free to experiment.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!