5

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

Cœur
  • 37,241
  • 25
  • 195
  • 267
yosoy89
  • 163
  • 1
  • 2
  • 7

1 Answers1

7

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.

stefanB
  • 77,323
  • 27
  • 116
  • 141
  • 1
    when you say: pt.put("a.path.to.float.value",3.14f); how it is represented in a .ini file? Remember .ini files are in the form [Elements] Elem1=Value1 ... – yosoy89 Mar 27 '13 at 21:08
  • I'd give it a try, see updated answer, I've added example code for ini file – stefanB Mar 27 '13 at 22:31
  • Can boost handle INI files with utf8 encoding? – seveves Nov 15 '13 at 17:34
  • @stefanB Please add the prefix `boost::property_tree::` to your call to `write_ini` - it took me 20 minutes to figure this out. I would do it myself, but edits like this usually get rejected. – Philipp Ludwig Feb 18 '19 at 13:46