How to read and write (or modify) .ini files using boost library?
Asked
Active
Viewed 1.8k times
5
-
2I need not only parse the .ini file, I also need to modify its values – yosoy89 Mar 26 '13 at 21:04
-
Is your question about regular expressions or which `boost` function to use? – Thomas Matthews Mar 26 '13 at 21:16
-
@yosoy89: You can also modify the values with `
`. – Jesse Good Mar 26 '13 at 21:17
1 Answers
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:
- ptree is too deep
- 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
-
1when 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
-
-
@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