2. Other types of options

Of course, not only strings can be specified in the configuration file. libConfuse can parse strings, integers, booleans and floating point values. These are the fundamental values, and they are all also available as lists. We'll talk more about lists in the next chapter.

The macros used to initialize a string, integer, boolean and a float is, respectively, CFG_STR(), CFG_INT(), CFG_BOOL(), CFG_FLOAT() and CFG_PTR(). All macros take three parameters: the name of the option, a default value and flags. To retrieve the values, use cfg_getstr(), cfg_getint(), cfg_getbool(), cfg_getfloat() or cfg_getptr(), respectively.

Let's introduce an integer option that tells us how many times to print the greeting:

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_INT("repeat", 1, CFGF_NONE),
10	        CFG_END()
11	    };
12	    cfg_t *cfg;
13	    int repeat;
14	
15	    cfg = cfg_init(opts, CFGF_NONE);
16	    if(cfg_parse(cfg, "hello.conf") == CFG_PARSE_ERROR)
17	        return 1;
18	
19	    repeat = cfg_getint(cfg, "repeat");
20	    while(repeat--)
21	        printf("Hello, %s!\n", cfg_getstr(cfg, "target"));
22	
23	    cfg_free(cfg);
24	    return 0;
25	}
26	

Here we have used the CFG_INT() macro to initialize an integer option named "repeat". The default value is 1 as in the standard greeting. The value is retrieved with cfg_getint().

But, wait a moment, what if the user specified a negative value for "repeat"? Or a too large positive value? libConfuse can handle that with a so-called validating callback. We'll come back to this problem later on, but we will first take a look at lists.