I have a configuration file myCfg.cfg
that looks like this :
keyA = 1.0
keyB = 2
keyC = "hello"
Note that all the settings are at the root of the configuration tree.
I want my C++ program to load that file then add a new setting whose key is keyD
and assign it integer value 5
. Eventually, MyCfg
should look like this in memory :
keyA = 1.0
keyB = 2
keyC = "hello"
keyD = 5
First the myCfg.cfg
file is loaded to construct MyCfg
. Then the setting keyD
must be added to the root of MyCfg
. The libconfig documentation indicates that the Setting::add()
method :
add[s] a new child setting with the given name and type to the setting, which must be a group
However, there isn't any group in MyCfg
… So how do I add a setting to the root of a Config object ?
It looks like all what you need is: getRoot ()
.
Here is example:
#include <iostream>
#include "libconfig.h++"
int main ()
{
libconfig::Config MyCfg;
std::string file = "myCfg.cfg";
try {
MyCfg.readFile (file.c_str () );
libconfig::Setting & root = MyCfg.getRoot ();
// This also works.
// libconfig::Setting & root = MyCfg.lookup ("");
libconfig::Setting & keyD = root.add ("KeyD", libconfig::Setting::TypeInt);
keyD = 5;
// You dont need it, but it's just for testing.
MyCfg.writeFile (file.c_str () );
}
catch (...) {
std::cout << "Error caused!" << std::endl;
}
return 0;
}