2016-07-15 3 views
2

libconfig C API를 사용하여 특성 파일을 구문 분석했습니다. 처음 두 속성에 null 값이 있습니다. 내 프로그램을 실행 한 후처음 두 값을 파싱 할 때 Libconfig 오류가 발생했습니다.

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 값을 가져옵니다.

출력 : 내가 처음 두 속성 값이 null 많은 샘플을 시도

Values of X : Y : Z = : : test 

;

답변

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

} 
+0

감사합니다. 이제 작동 중 그럼 왜 세 번째 속성 값이 null이 아닌지. –