Search code examples
clibconfig

LibConfig - How to get container list


I have the following configuration, I know how to loop through each of the sections with config_lookup(), but I do not know how to find the name of each of the section!

downloads = {

    john = {

        configid = 1;
        status = 1;
        configname = "John's File Server";
        configtype = 0;
        ipaddress = "192.168.1.100";
        username = "test";
        password = "test";
    };

    jill = {

        configid = 3;
        status = 1;
        configname = "Jill's file server";
        configtype = 0;
        ipaddress = "10.10.20.50";
        username = "test";
        password = "test";
    };
};

I was wondering how to get the section name ie., jack & jill with libconfig. I know how to get the values in jack and jill, because I know the param names beforehand, but jack and jill is user configed. Shortened code goes like this-

config_t cfg;
config_setting_t *setting;
int i = 0, count = 0;

if(!config_read_file(&cfg, filename))
    return false;

if((setting = config_lookup(&cfg, "downloads")) != NULL)
{
    count = config_setting_length(setting);

    for(i = 0; i < count; ++i)
    {
        // do stuff
    }
}

config_destroy(&cfg);

Any idea how to do it? Thanks in advance


Solution

  • Ok so since Ian didnt post an answer, I am. Credit goes to Ian.

    config_t cfg;
    config_setting_t *setting;
    int i = 0, count = 0;
    
    if(!config_read_file(&cfg, filename))
        return false;
    
    if((setting = config_lookup(&cfg, "downloads")) != NULL)
    {
        count = config_setting_length(setting);
    
        for(i = 0; i < count; ++i)
        {
            config_setting_t *nodes = config_setting_get_elem(setting, i);
            const char *section_name = = config_setting_name(nodes); // Section name, no need to free, the library manages that;
        }
    }
    
    config_destroy(&cfg);