最近项目中遇到的配置文件升级功能(需要保留原始配置),在网上没有找到比较合适的例子,所以自己便写了一个,代码比较简单,使用的是libconfig编写的。只为提供一个简单的例子,所以里面只有一层配置,不保证效率只为实现功能。
思路:将源文件的内容读出后重新添加到新配置文件中,但是没有注重效率算法,可能配置比较大时速度不够
配置文件:
1.cfg
version: "2.0.1";
familiy1 : {
open_door = 1;
open_music = 0;
};
familiy2 : {
open_door = 1;
open_music = 1;
};
2.cfg
version: "2.0.2";
familiy1 : {
open_door = 0;
open_music = 0;
open_window = 1;
};
familiy2 : {
open_door = 0;
open_music = 0;
open_window = 0;
};
代码:
void update_hm9_cfg_file(char *old, char *new)
{
config_t cfgo, cfgn, *cfgop, *cfgnp;
cfgop = &cfgo;
cfgnp = &cfgn;
config_init(cfgnp);
config_set_options(cfgnp, (CONFIG_OPTION_FSYNC));
config_init(cfgop);
if (CONFIG_FALSE == config_read_file(cfgop, old)) {
printf("%s: %d\n", config_error_text(cfgop), config_error_line(cfgop));
}
if (CONFIG_FALSE == config_read_file(cfgnp, new)) {
printf("%s: %d\n", config_error_text(cfgnp), config_error_line(cfgnp));
}
char content[32];
config_setting_t *root = config_root_setting(cfgop);
int length = config_setting_length(root);
for (int i = 0; i < length; i++) {
config_setting_t *parent_elem = config_setting_get_elem(root, i);
int elem_l = config_setting_length(parent_elem);
char *parent = config_setting_name(parent_elem);
config_setting_t *parent_n = config_lookup(cfgnp, parent);
for (int j = 0; j < elem_l; j++) {
config_setting_t *child_elem = config_setting_get_elem(parent_elem, j);
char *child = config_setting_name(child_elem);
int val = config_setting_get_int(child_elem);
sprintf(content, "%s.%s", parent, child);
config_setting_set_int(config_setting_lookup(parent_n, child), val);
}
}
config_write_file(cfgnp, new);
config_destroy(cfgop);
config_destroy(cfgnp);
}
int main()
{
update_hm9_cfg_file(1.cfg, 2.cfg);
}
合并后的配置文件1.cfg
version: "2.0.2";
familiy1 : {
open_door = 1;
open_music = 0;
open_window = 1;
};
familiy2 : {
open_door = 1;
open_music = 1;
open_window = 0;
};