5. Parsing from internal buffers
Prev |  | Next

## 5. Parsing from internal buffers

So far, we have only parsed configuration data from files. libConfuse can also parse buffers, or in-memory character strings. We will use this to fix a problem in the previous code.

The problem is that without a configuration file, the hello program will not print anything. We want it to at least print the standard greeting "Hello, World!" if no configuration file is available.

We can't have a default value for a section that can be specified multiple times (ie, a section with the CFGF_MULTI flag set). Instead we will parse a default configuration string if no section has been parsed:

    1	#include <stdio.h>
    2	#include <confuse.h>
    3
    4	int main(void)
    5	{
    6	    /* ... setup options ... */
    7
    8	    cfg = cfg_init(opts, CFGF_NONE);
    9	    cfg_parse(cfg, "hello.conf");
    10
    11	    if(cfg_size(cfg, "greeting") == 0)
    12	    {
    13	        cfg_parse_buf(cfg, "greeting Hello {}");
    14	    }
    15
    16	    /* ... print the greetings ... */
    17	}

Only the changes from the previous code is shown here. We check if the size of the "greeting" section is zero (ie, no section has been defined). In that case we call `cfg_parse_buf()` to parse a default in-memory string "greeting Hello {}". This string defines a greeting section with title Hello, but without any sub-options. This way we rely on the default values of the (sub-)options "targets" and "repeat".

When this program is run, it issues the well-known standard greeting "Hello, World!" if no configuration file is present.

Prev |  | Next
4. Using sections | Home | 6. Validating callback functions