libConfuse tutorial
|  | Next

## libConfuse tutorial

### Martin Hedenfalk

## 1. Introducing libConfuse in an existing program

Consider this simple program:

    1	#include <stdio.h>
    2
    3	int main(void)
    4	{
    5	    printf("Hello, World!\n");
    6	    return 0;
    7	}
    8

Simple enough, but we want to extend the program so we can greet others. Maybe we don't want to greet the whole world, just our neighbour. We use libConfuse to let the user decide whom to greet.

    1	#include <stdio.h>
    2	#include <confuse.h>
    3
    4	int main(void)
    5	{
    6	    cfg_opt_t opts[] =
    7	    {
    8	        CFG_STR("target", "World", CFGF_NONE),
    9	        CFG_END()
    10	    };
    11	    cfg_t *cfg;
    12
    13	    cfg = cfg_init(opts, CFGF_NONE);
    14	    if(cfg_parse(cfg, "hello.conf") == CFG_PARSE_ERROR)
    15	        return 1;
    16
    17	    printf("Hello, %s!\n", cfg_getstr(cfg, "target"));
    18
    19	    cfg_free(cfg);
    20	    return 0;
    21	}
    22

All programs using libConfuse must first include the `confuse.h` header file. This is done on line 2.

On line 6 - 10, the options that should be recognized are defined in an array of cfg_opt_t structs. This is passed to the `cfg_init` function on line 13. The resulting cfg_t context is used by `cfg_parse()`, which reads the configuration file "hello.conf". When reading the configuration file, only options defined in the array of options passed to `cfg_init()` are recognized.

The friendly greeting is now replaced with a parameter read from the configuration file. The value of the `target` option is retrieved with `cfg_getstr(cfg, "target")`.

Lets take a look at the configuration file hello.conf:

    # this is the configuration file for the hello program

    target = "Neighbour"

Here, the target option is set to the string value "Neighbour". What if the configuration file was empty or didn't exist? Then the default value for the `target` option would be used. When we initialized our options, the second parameter to the `CFG_STR()` macro specified the default value. Thus, if no `target` option was specified in the configuration file, the hello program would have printed the standard greeting "Hello, World".

### 1.1. Environment variables in values

What else can we do in the configuration file? We can set the value to an environment variable:

    target = ${USER}

This results in the hello program greeting the user who runs it. On some systems, the USER variable might not be available, so we want to specify a default value in those cases:

    target = ${USER:-User}

Now, if the USER environment variable is unset, the string "User" will be used instead.

|  | Next
|  | 2. Other types of options