using config files in C

Requirement is to move the data out of C programs and let the program use a config file for the data. say we have a file called data.ini.

$ cat data.ini
position:{
x = 50;
y = 100;
}

$ cat prog.c
#include <libconfig.h>
int main(){
  long int x = 0;
  config_t* config;

  config_init(config);
  // read config file
  config_read_file(config, "data.ini");

  // get the value
  if( config_lookup_int(config, "position.x", &x) == CONFIG_FALSE ){
    printf("failed to lookup - position.x\n");
    return 1;
  }

  printf("x = %d\n", (int)x);
  return 0;
}

Compile the program using the option “-lconfig”

$ gcc -lconfig prog.c

You may need libconfig-dev,
$ sudo apt-get install libconfig-dev

Reference:
libconfig manual
Configuration file (wikipedia)

Advertisements

2 thoughts on “using config files in C

  1. very thank you for your code as I get problems with the example1.c provided by the libconfig to compile…. the only point is that your code is not working perfectley in my case… I think it should be config_init(&config); and so….otherwise I get s segmentation error…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s