How to read and write (or modify) .ini files using boost library?
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With