2
votes

I using libconfig C api for parsing properties file. I got null value in first two properties.

test.properties

 x = "hello";
 y = "world";
 z = "test" ;

config.c

char * getValueByKey(char * file_name , char * key) {
    config_t cfg;               
    config_setting_t *setting;
    const char * value;

    config_init(&cfg);


    if (!config_read_file(&cfg, file_name))
    {
        printf("\n%s:%d - %s", config_error_file(&cfg), config_error_line(&cfg), config_error_text(&cfg));
        config_destroy(&cfg);
        exit(1);
    }
    if (config_lookup_string(&cfg, key , &value)){
        config_destroy(&cfg);
        printf("Hello %s\n",value );
        return (char *) value ;
    }
    else{
        printf("\nNo 'filename' setting in configuration file.");
        config_destroy(&cfg);
    }
}

int main(){
    char * x = getValueByKey("test.properties" , "x");
    char * y = getValueByKey("test.properties" , "y");
    char * z = getValueByKey("test.properties" , "z");
    printf("Values of X : Y : Z  = %s : %s : %s", x, y, z);
}

After run my programme I get only Z value.

output:

Values of X : Y : Z  =  :  : test 

I try many sample I first two properties value is null;

1

1 Answers

0
votes

When you are calling config_destroy() library will free all the memory allocated by it. So before calling config_destroy() you need to save your result some where else.

#include <stdio.h>
#include <libconfig.h>
#include <stdlib.h>


char value[100];
char * getValueByKey(char * file_name , char * key,char* value1) {
    config_t cfg;
    config_setting_t *setting;
    const char *value;
    config_init(&cfg);
    if (!config_read_file(&cfg, file_name))
    {
        printf("\n%s:%d - %s", config_error_file(&cfg), config_error_line(&cfg), config_error_text(&cfg));
        config_destroy(&cfg);
        exit(1);
    }
    if (config_lookup_string(&cfg, key , &value)){
        strcpy(value1,value);
        config_destroy(&cfg);
        //printf("%s:%s\n",key,value1);
        //printf("Hello %s\n",value );
        return (char *) value1 ;
    }
    else{
        printf("\nNo 'filename' setting in configuration file.");
        config_destroy(&cfg);
    }
}

int main(){
    char * x = getValueByKey("test.properties" , "x",value);
    printf("X = %s\n", x);
    char * y = getValueByKey("test.properties" , "y",value);
    printf("Y = %s\n", y);
    char * z = getValueByKey("test.properties" , "z",value);
    printf("Z = %s\n", z);

}