Question

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?

Was it helpful?

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.

OTHER TIPS

I came across this question while searching for a way to have libconfig write output to a string instead of a file. I see that there's no acceptable answer here, so I thought I would provide one for posterity, even though the question is over 3 years old.

#include <stdint.h>
#include <string>

#include "libconfig.h++"

int32_t
main (void) {
    libconfig::Config config;
    std::string file = "test.conf";

    try {
        config.readFile(file.c_str());

        libconfig::Setting &limited = config.lookup("video.fps.limited");
        libconfig::Setting &value = config.lookup("video.fps.value");

        limited = false;
        value = 60;

        config.writeFile(file.c_str());
    }
    catch (...) {
        // Do something reasonable with exceptions here.  Do not catch (...)
    }

    return 0;
}

Hope that helps someone!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top