Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

boost

ini

How to read and write (or modify) .ini files using boost library?

like image 822
yosoy89 Avatar asked Mar 26 '13 20:03

yosoy89


1 Answers

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.

like image 149
stefanB Avatar answered Oct 13 '22 00:10

stefanB