28 Feb

An Alternative to XML

My new weapon of choice. libconfig is a configuration file parser that supports arrays, named and typed members, selection by path (e.g. cfg.users.[3].name) and more. That is, it has basically all the useful (as in 80% of cases) features of XML and none of the bad. There’s a minimal but well defined structure that will work for most situations and that can be used to enforce e.g. all array items having to be of the same type. There’s no overkill markup so it’s easy to read and write by humans. The library can also write the settings tree into a text file.

The configuration files look like this:

screen = { width = 300; height = 200; }
users = ( { name = "Torgo"; items = [ "Item 1", "Item 2" ]; } );

And in C you would do something like this:

int screen_height = 100;
const char *name;
config_init(&cfg);
config_read_file(&cfg, "config");
if (!config_lookup_int(&cfg, "screen.height", &screen_height))
  puts("Using default screen height");
if (config_lookup_string(&cfg, "users.[0].name", &name))
  puts(name);
config_destroy(&cfg);

You can also iterate the setting tree without the path for easier array or tree traversal. In all, I would say it involves less work compared to any XML library, especially in C. I like to think it’s a good example of software designed by the same guy who also uses it and not by some external committee.