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