I am trying to create a simple configuration file that looks like this
url = http://mysite.com
file = main.exe
true = 0
when the program runs, I would like it to load the configuration settings into the programs variables listed below.
string url, file;
bool true_false;
I have done some research and this link seemed to help (nucleon's post) but I can't seem to get it to work and it is too complicated to understand on my part. Is there a simple way of doing this? I can load the file using ifstream
but that is as far as I can get on my own. Thanks!
Why not trying something simple and human-readable, like JSON (or XML) ?
There are many pre-made open-source implementations of JSON (or XML) for C++ - I would use one of them.
And if you want something more "binary" - try BJSON or BSON :)
A naive approach could look like this:
Now you can access each option value from the global
options
map anywhere in your program. If you want castability, you could make the mapped type aboost::variant
.Here is a simple work around for white space between the '=' sign and the data, in the config file. Assign to the istringstream from the location after the '=' sign and when reading from it, any leading white space is ignored.
Note: while using an istringstream in a loop, make sure you call clear() before assigning a new string to it.
In general, it's easiest to parse such typical config files in two stages: first read the lines, and then parse those one by one.
In C++, lines can be read from a stream using
std::getline()
. While by default it will read up to the next'\n'
(which it will consume, but not return), you can pass it some other delimiter, too, which makes it a good candidate for reading up-to-some-char, like=
in your example.For simplicity, the following presumes that the
=
are not surrounded by whitespace. If you want to allow whitespaces at these positions, you will have to strategically placeis >> std::ws
before reading the value and remove trailing whitespaces from the keys. However, IMO the little added flexibility in the syntax is not worth the hassle for a config file reader.(Adding error handling is left as an exercise to the reader.)
I've searched config parsing libraries for my project recently and found these libraries:
As others have pointed out, it will probably be less work to make use of an existing configuration-file parser library rather than re-invent the wheel.
For example, if you decide to use the Config4Cpp library (which I maintain), then your configuration file syntax will be slightly different (put double quotes around values and terminate assignment statements with a semicolon) as shown in the example below:
The following program parses the above configuration file, copies the desired values into variables and prints them:
The Config4Cpp website provides comprehensive documentation, but reading just Chapters 2 and 3 of the "Getting Started Guide" should be more than sufficient for your needs.