3. Introducing lists

That was easy. Now let's extend the program a bit so we can greet more than one "target". We'd like to be able to specify a list of targets to greet.

The list versions of the initialization macros are named CFG_STR_LIST(), CFG_INT_LIST(), CFG_BOOL_LIST() and CFG_FLOAT_LIST(). They take the same parameters as the non-list versions, except the default value must be a string surrounded by curly braces.

The modified program is shown below:

1	#include <stdio.h>
2	#include <confuse.h>
3	
4	int main(void)
5	{
6	    cfg_opt_t opts[] =
7	    {
8	        CFG_STR_LIST("targets", "{World}", CFGF_NONE),
9	        CFG_INT("repeat", 1, CFGF_NONE),
10	        CFG_END()
11	    };
12	    cfg_t *cfg;
13	    int repeat;
14	    int i;
15	
16	    cfg = cfg_init(opts, CFGF_NONE);
17	    if(cfg_parse(cfg, "hello.conf") == CFG_PARSE_ERROR)
18	        return 1;
19	
20	    repeat = cfg_getint(cfg, "repeat");
21	    while(repeat--)
22	    {
23	        printf("Hello");
24	        for(i = 0; i < cfg_size(cfg, "targets"); i++)
25	            printf(", %s", cfg_getnstr(cfg, "targets", i));
26	        printf("!\n");
27	    }
28	
29	    cfg_free(cfg);
30	    return 0;
31	}
32	

Three things are a bit different here. First, the macro to initialize the "targets" option is CFG_STR_LIST(). This tells libConfuse that "targets" is a list of strings. Second, the default value in the second parameter is surrounded by curly braces. This is needed to indicate to libConfuse where the list of values ends.

The third change is in the printing of the greeting. First we print the "Hello" string. Then we loop through all values found for the "targets" option. The number of values is retrieved with the cfg_size() function. The string values are then retrieved with cfg_getnstr(), which is an indexed version of cfg_getstr(). In fact, cfg_getstr() is equivalent to cfg_getnstr() with an index of zero.

In the configuration file hello.conf, we can now specify a list of targets to greet:

# this is the configuration file for the hello program

targets = {"Life", "Universe", "Everything"}
repeat = 1
        

The output of the hello program, run with the above configuration file, is: "Hello, Life, Universe, Everything!"

Again, if no targets were configured, the greeting would have been the standard "Hello, World!".