In C, how to configure the initial settings for some program, using key-value pairs, with any or all of: a plain text configuration file, environment variables, and options on the command line. Also, how to decide which method's values overide those from either of the other two. Then if values have been changed, to optionally update the configuration file.
What's the simplest way to do this, and what if any, are the most accepted methods? Is there a, preferably small, open source program that gives a good example of how this can be done?
Eric Raymond covers a lot of this in Section 10 of The Art of Unix Programming Obviously this is Unix centric, but most of the principles can be applied in any OS.
The basics:
Which settings source should override each other depends on the application, but in my opinion generally commandline argument > environment variable > configuration file makes most sense.
Here is an example of getting configuration from environment and commandline, with commandline overriding environment:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, const char* const* argv) {
int i;
const char* myConfigVar;
// get default setting from environment
myConfigVar = getenv("MY_CONFIG_VAR");
// if the variable wasn't defined, initialize to hardcoded default
if (!myConfigVar)
myConfigVar = "default value";
// parse commandline arguments
// start at 1, because argv[0] contains the name of the program
for (i = 1; i < argc; ++i) {
if (strcmp("--my-config-var", argv[i]) == 0) {
if (i + 1 < argc)
myConfigVar = argv[i + 1];
else
printf("missing value for my-config-var argument\n");
}
}
printf("myConfigVar = '%s'\n", myConfigVar);
return 0;
}
You already see it becomes very long and tedious very soon, so better use an existing library if one exists for your desired target platform(s), or at least factor this kind of code into a number of functions.
Another interesting option is to bind a scripting language to your application, then you could make your application only read and "execute" your settings file, and the user could configure the settings file to read some settings from the environment and some from the commandline, for example. It really depends on type and size of the application and your target audience whether this is worth doing though.
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