解析前两个值时出现Libconfig错误

时间:2016-07-15 11:46:20

标签: c libconfig

我使用libconfig C api来解析属性文件。 我在前两个属性中得到了空值。

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);
}

运行我的程序后,我只得到Z值。

输出:

Values of X : Y : Z  =  :  : test 

我尝试了很多样本​​我前两个属性值为null;

1 个答案:

答案 0 :(得分:0)

当您调用config_destroy()时,库将释放它分配的所有内存。因此,在致电config_destroy()之前,您需要将结果保存在其他地方。

#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);

}