【问题标题】:Libconfig error when parse first two values解析前两个值时出现 Libconfig 错误
【发布时间】:2016-11-18 14:50:16
【问题描述】:

我使用 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 

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

【问题讨论】:

    标签: c libconfig


    【解决方案1】:

    当您调用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);
    
    }
    

    【讨论】:

    • 谢谢!现在它正在工作那么为什么上面的第三个属性值不为空。
    猜你喜欢
    • 2011-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-12
    • 2022-08-05
    • 1970-01-01
    • 2015-06-05
    • 1970-01-01
    相关资源
    最近更新 更多