我在我的配置文件中为选项定义了一个结构,并在“config.h”文件中定义了一个指向该结构的指针,我使用 libconfig 读取配置文件并在文件“config.c”中定义的函数 get_config() 中设置值。在主函数中,我初始化指向结构的指针并调用 get_config() 函数。libconfig 运行良好,可以正确打印结构字段的值,但是当我在主函数中打印相同的字段时,它们的值不正确!
“配置.h”
#include <stdio.h>
#include <stdlib.h>
#include <libconfig.h>
typedef struct
{
int buffer_size;
const char * DBusername;
const char * DBpassword;
}conf;
conf *config;
int get_config();
“配置.c”
#include "config.h"
int get_config()
{
config_t cfg;
config_setting_t *setting;
config_init(&cfg);
/* Read the file. If there is an error, report it and exit. */
if(! config_read_file(&cfg, "config.cfg"))
{
fprintf(stderr, "%s:%d - %s\n", config_error_file(&cfg),
config_error_line(&cfg), config_error_text(&cfg));
config_destroy(&cfg);
return(EXIT_FAILURE);
}
if(config_lookup_int(&cfg, "buffersize", &config->buffer_size))
printf("buffersize: %d\n\n", config->buffer_size);
else
fprintf(stderr, "No 'buffersize' setting in configuration file.\n");
if(config_lookup_string(&cfg, "DBusername", &config->DBusername))
printf("DBusername: %s\n\n", config->DBusername);
else
fprintf(stderr, "No 'DBusername' setting in configuration file.\n");
if(config_lookup_string(&cfg, "DBpassword", &config->DBpassword))
printf("DBpassword: %s\n\n", config->DBpassword);
else
fprintf(stderr, "No 'DBpassword' setting in configuration file.\n");
config_destroy(&cfg);
return(EXIT_SUCCESS);
}
“商店.c”
int main(){
config = (conf*) malloc(sizeof(conf));
if(get_config() == EXIT_FAILURE)
return 0;
printf("\n%s", config->DBusername);
printf("\n%s", config->DBpassword);
printf("\n%d", config->buffer_size);
}