[LC++]Containers of Containers

Davide Bolcioni db_linuxcpp at yahoo.it
Tue Dec 24 04:40:01 UTC 2002


Greetings,

Paul M Foster wrote:
> I'm looking at creating a program to read various configuration files,
> with various syntaxes. I can use flex et al to parse the various config
> syntaxes, but all of them share the characteristic of having a name
> equal some value. In some cases, config files will yield nested
> name/value pairs, like Windows ini files.

In my opinion, the problem of a hierarchy of <name, value> pairs (of
which .ini files are but one brain-damaged instance) is best solved
by looking at the filesystem. I would suggest to store all values as
strings (more on this later) and use a filesystem-like "path" as key
in a private std::map or SGI hash_map.

This would be used like this:

   my_lib::configuration conf;

   std::string hd_type = conf("computer/hard_drive/type");
   int hd_capacity = conf("computer/hard_drive/capacity");

If a piece of code just deals with a subtree, for example
"computer/hard_drive", you just pass the prefix as one of the
parameters.

A more general purpose approach, possibly demanding a more
sophisticated data structure behind the scenes, would allow you to
iterate the keys of said subtree (you have to know them in
order to the retrieve them if a map is used, I am afraid).

Regarding values, you might want to store them as strings or even as
const char* if your input is staying around long enough; conversion
occurs when you pull the value - at which point you have probably
enough context to tell if the value is valid or not and provide a
readable error message (using an exception, I would guess).

Consider your own example: the knowledge that "40G" means
40 * 2 ^ 30 is in the application pulling the data, not in the
code dealing with configuration. A physicist with Fortran
background might want it to mean 40 * 9.8 m/s², after all.

Finally, one plea ... while wearing my sysadmin hat, I often cursed
programmers who read configuration files only when a daemon starts
up. Please consider supporting "re-read on SIGHUP" for daemons,
thank you.

Davide Bolcioni
-- 
Paranoia is an afterthought.




More information about the tuxCPProgramming mailing list