基于libconfig的配置文件升级

最近项目中遇到的配置文件升级功能(需要保留原始配置),在网上没有找到比较合适的例子,所以自己便写了一个,代码比较简单,使用的是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;
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值