Many applications that you will develop operate on input parameters set by the user. For example, it could be the color or position of some graphical elements or parameters used to set up communication with other applications. Reading configurations from external files is necessary for your applications. We will use a built-in Cinder support for reading and writing XML files to implement the configuration persistence mechanism.
Create two configurable variables in the main class: the IP address and the port of the host we are communicating with.
string mHostIP; int mHostPort;
Now we will implement the loadConfig
and saveConfig
methods and use them to load the configuration on application startup and save the changes while closing.
#include "cinder/Utilities.h" #include "cinder/Xml.h"
void MainApp::loadConfig() { try { XmlTree doc( loadFile( getAppPath() / fs::path("config.xml") ) ); XmlTree &generalNode = doc.getChild( "general" ); mHostIP = generalNode.getChild("hostIP").getValue(); mHostPort = generalNode.getChild("hostPort").getValue<int>(); } catch(Exception e) { console() << "ERROR: loading/reading configuration file." << endl; } } void MainApp::saveConfig() { std::string beginXmlStr( "<?xml version="1.0" encoding="UTF-8" ?>" ); XmlTree doc( beginXmlStr ); XmlTree generalNode; generalNode.setTag("general"); generalNode.push_back( XmlTree("hostIP", mHostIP) ); generalNode.push_back( XmlTree("hostPort", toString(mHostPort)) ); doc.push_back(generalNode); doc.write(writeFile( getAppPath() / fs::path("config.xml")) ); }
setup
method, inside our main class, we will put:// setup default values mHostIP = "127.0.0.1"; mHostPort = 1234; loadConfig();
shutdown
method as follows:void MainApp::shutdown() { saveConfig(); }
shutdown
method in the main class:void shutdown();
The first two methods, loadConfig
and saveConfig
, are essential. The loadConfig
method tries to open the config.xml
file and find the general
node. Inside the general
node should be the hostIP
and hostPort
nodes. The values of these nodes will be assigned to corresponding variables in our application: mHostIP
and mHostPort
.
The
shutdown
method is automatically triggered by Cinder just before the application closes, so our configuration values will be stored in the XML file when we quit the application. Finally, our configuration XML file looks like this:
<?xml version="1.0" encoding="UTF-8" ?> <general> <hostIP>127.0.0.1</hostIP> <hostPort>1234</hostPort> </general>
You can see clearly that the nodes are referring to application variables.
18.225.255.86