c++configurationlibconfig

Libconfig edit config value


I am using libconfig to read/wirte config files in my C++ game.

Right now I just have this one config file called video.cfg:

#Video config file
video:
{
    fps:
    {
      limited = true;
      value = 20;
    };
};

This config file handles the video settings of the game.

I am trying to write a very basic console program that modifies this values based on user input. However I have no idea how to do this. I can't find anything in libconfig manual and nothing on Google.

So how do you edit values in Libconfig?


Solution

  • #include <libconfig.h>
    
    int main() {
       config_t cfg;
       config_setting_t *vid_fps_lim = 0;
       config_setting_t *vid_fps_val = 0;
    
       config_init(&cfg);
    
       if (config_read_file(&cfg, "myconfig") == CONFIG_TRUE) {
    
          /* lookup the settings we want */
          vid_fps_lim = config_lookup(&cfg, "video.fps.limited");
          vid_fps_val = config_lookup(&cfg, "video.fps.value");
    
          /* print the current settings */
          printf("video.fps.limited = %i\n", config_setting_get_bool(vid_fps_lim));
          printf("video.fps.value = %i\n", config_setting_get_int(vid_fps_val));
    
          /* modify the settings */
          config_setting_set_bool(vid_fps_lim, 1);
          config_setting_set_int(vid_fps_val, 60);
    
          /* write the modified config back */
          config_write_file(&cfg, "myconfig");
       }
    
       config_destroy(&cfg);
    
       return 0;
    }
    

    I named the file "lcex.c" and the config file "myconfig" It builds and runs on my Debian Linux machine using the following...

    gcc `pkg-config --cflags libconfig` lcex.c -o lcex `pkg-config --libs libconfig`
    
    ./lcex
    

    Open your config file after running the app and you should see that the values have been updated.

    Disclaimer...error handling left out to make it easier to read. I didn't build with -Wall, etc. As with any API, read the docs and handle potential errors.