Table of Contents

demo1

配置文件libconfigdemo.cfg

读取代码config_read_file.c

结果:

demo2

头文件EmbGW.h

配置文件default.cfg

源代码config.c

编译运行


demo1

配置文件libconfigdemo.cfg

# authenticatorname = "JP";
enabled = false;
length = 186;ldap = {host = "ldap.example.com";base = "ou=usr,o=example.com";  /* adapt this */retries = [10, 15, 20, 60];   // Use more than 2
};

读取代码config_read_file.c

#include <stdio.h>
#include <stdlib.h>
#include <libconfig.h>#define CONFIG_FILE "libconfigdemo.cfg"int main(void)
{//the type of configconfig_t cfg, *cf;const config_setting_t *retries;//the setting of configconst char *base = NULL;int count, n, enabled;cf = &cfg;config_init(cf); //initial configif (!config_read_file(cf, CONFIG_FILE)) { //read the config filefprintf(stderr, "%s:%d - %s\n",config_error_file(cf),config_error_line(cf),config_error_text(cf));config_destroy(cf);return(EXIT_FAILURE);}if (config_lookup_bool(cf, "enabled", &enabled)) //search "enabled"printf("Enabled: %s\n", enabled ? "Yep" : "Nope");else printf("Enabled is not defined\n");if (config_lookup_string(cf, "ldap.base", &base)) //read stringprintf("Host: %s\n", base);retries = config_lookup(cf, "ldap.retries"); //read a arraycount = config_setting_length(retries);printf("I have %d retries:\n", count);for (n = 0; n < count; n++) {printf("\t#%d. %d\n", n + 1,config_setting_get_int_elem(retries, n));}config_destroy(cf);return 0;
}

结果:

$ ./a.out
Enabled: Nope
Host: ou=usr,o=example.com
I have 4 retries:#1. 10#2. 15#3. 20#4. 60

demo2

头文件EmbGW.h

/*************************************************************************> File Name: EmbGW.h> Author: Hac> Mail: hac@zju.edu.cn> Created Time: Thu 12 May 2016 09:26:50 AM CST************************************************************************//** Macros*/
#define MAXSERVERNUM 16
#define MAXSENSORNUM 4#define BT          1
#define R430        2
#define BIN         3
#define HTTP        4/** Configuration*/
unsigned int server_num = 0;
char server_name[MAXSERVERNUM][16];
char server_addr[MAXSERVERNUM][64]; // ip address or domain name of web server
unsigned int server_type[MAXSERVERNUM]; // BIN or HTTPunsigned int sensor_num = 0;
char sensor_name[MAXSENSORNUM][16];
char sensor_dev[MAXSENSORNUM][32]; // path of serial devices
unsigned int sensor_type[MAXSENSORNUM]; // BlueTooth or Radio430

配置文件default.cfg

gateway: {upload = ({name = "server1";port = 8080;addr = "10.214.128.100";type = "BIN";},{name = "server2";port = 8080;addr = "10.214.128.112";type = "HTTP";});download = ({name = "sensor1";device = "/dev/ttyAMA0";type = "BT";},{name = "sensor2";device = "/dev/ttyUSB0";type = "R430";});
};

源代码config.c

/*************************************************************************> File Name: config.c> Author: Hac> Mail: hac@zju.edu.cn> Created Time: Thu 12 May 2016 08:55:36 AM CST************************************************************************/#include "stdio.h"
#include <stdlib.h>
#include <string.h>
#include <libconfig.h>
#include "EmbGW.h"#define path "default.cfg"void Load_Conf() {config_t cfg;config_setting_t *upload, *download;//const char *path = getenv("CONF_PATH");config_init(&cfg);/* Read the configuration file. If not exists, exit */if (!config_read_file(&cfg, path)) {fprintf(stderr, "Error: %s:%d - %s\n", config_error_file(&cfg),config_error_line(&cfg), config_error_text(&cfg));config_destroy(&cfg);exit(1);}printf("Open file '%s' --- DONE\n", path);/* check UPLOAD && DOWNLOAD */upload = config_lookup(&cfg, "gateway.upload");download = config_lookup(&cfg, "gateway.download");if (upload == NULL || download == NULL) {fprintf(stderr, "Error: Incomplete configuration: you have to specify both #upload and #download.\n");exit(1);}/* Load configuration into global variables */// UPLOAD{int i;int count = config_setting_length(upload);if (count > MAXSERVERNUM) {printf("Warning: More than %d servers are provided, while only the first %d will be used.\n", MAXSERVERNUM
, MAXSERVERNUM);count = MAXSERVERNUM;}for (i = 0; i < count; ++i) {config_setting_t *server = config_setting_get_elem(upload, i);const char *name, *addr, *type;int port;if (!(config_setting_lookup_string(server, "name", &name)&& config_setting_lookup_int(server, "port", &port)&& config_setting_lookup_string(server, "addr", &addr)&& config_setting_lookup_string(server, "type", &type))) {fprintf(stderr, "Error: Cannot resolve the %dth item in #UPLOAD field. Please review the config file.\
n", i);exit(1);}strncpy(server_name[server_num], name, sizeof(server_name[i-1]));strncpy(server_addr[server_num], addr, sizeof(server_addr[i-1]));if (strcmp(type, "BIN") == 0)server_type[server_num] = BIN;else if(strcmp(type, "HTTP") == 0)server_type[server_num] = HTTP;else {fprintf(stderr, "Error: Cannot resolve 'type = %s' in the %dth item of #UPLOAD field.\n", type, i);exit(1);}server_num++;}}// DOWNLOAD{int i;int count = config_setting_length(download);if (count > MAXSENSORNUM) {printf("Warning: More than %d sensors are provided, while only the first %d will be used.\n", MAXSENSORNUM
, MAXSENSORNUM);count = MAXSENSORNUM;}for (i = 0; i < count; ++i) {config_setting_t *sensor = config_setting_get_elem(download, i);const char *name, *device, *type;if (!(config_setting_lookup_string(sensor, "name", &name)&& config_setting_lookup_string(sensor, "device", &device)&& config_setting_lookup_string(sensor, "type", &type))) {fprintf(stderr, "Error: Cannot resolve the %dth item in #DOWNLOAD field. Please review the config file
.\n", i);exit(1);}strncpy(sensor_name[sensor_num], name, sizeof(sensor_name[i-1]));strncpy(sensor_dev[sensor_num], device, sizeof(sensor_dev[i-1]));if (strcmp(type, "BT") == 0)sensor_type[sensor_num] = BT;else if(strcmp(type, "R430") == 0)sensor_type[sensor_num] = R430;else {fprintf(stderr, "Error: Cannot resolve 'type = %s' in the %dth item of #DOWNLOAD field.\n", type, i);exit(1);}sensor_num++;}}printf("Load configuration --- DONE\n");
}
int main(int argc, char *argv[])
{Load_Conf();/* test */unsigned int i;for (i = 0; i < server_num; i++) {printf("%s %s %d\n", server_name[i], server_addr[i], server_type[i]);}for (i = 0; i < sensor_num; i++) {printf("%s %s %d\n", sensor_name[i], sensor_dev[i], sensor_type[i]);}return 0;
}

编译运行

$ gcc config.c -lconfig
$ ./a.out
Open file 'default.cfg' --- DONE
Load configuration --- DONE
server1 10.214.128.100 3
server2 10.214.128.112 4
sensor1 /dev/ttyAMA0 1
sensor2 /dev/ttyUSB0 2

https://github.com/ZJUemb/Config/blob/master/config.c

用libconfig读取配置文件相关推荐

  1. 基于Golang的监听读取配置文件的程序包开发——simpleConfig_v1

    基于Golang的监听&读取配置文件的程序包开发--simpleConfig_v1 [阅读时间:约10分钟] 一.配置文件概述 二.系统环境&项目介绍 1.系统环境 2.项目的任务要求 ...

  2. LabVIEW保存、读取配置文件

    目录 1.保存配置文件 2.读取配置文件 在软件项目开发过程中避免不了要将数据保存到本地,例如,登录信息.账户.密码等.保存数据到本地的方式有很多种,本篇博文主要分享LabVIEW内置的保存.读取配置 ...

  3. java读取配置文件信息

    String configfile = "cfg/client.cfg";// 读取配置文件账号密码Properties props = new Properties();Inpu ...

  4. 利用java反射机制 读取配置文件 实现动态类载入以及动态类型转换

    作者:54dabang 在spring的学习过程之中,我们能够看出通过配置文件来动态管理bean对象的优点(松耦合 能够让零散部分组成一个总体,而这些总体并不在意之间彼此的细节,从而达到了真正的物理上 ...

  5. .NET Core 6.0之读取配置文件

    在ASP.NET Core 6.0中,默认配置文件是appsettings.json,该文件存储的内容为JSON格式的字符串,我们一般都将程序的配置放在这个文件里面,提供给程序使用,那么我们该如何操作 ...

  6. SpringBoot 读取配置文件中参数全面教程

    一.简介 在日常开发使用 SpringBoot 框架时,经常有一些配置信息需要放置到配置文件中,我们需要手动读取这些配置到应用中进行一些逻辑,这里整理了一些常用读取配置的方法,简单介绍一下. 1.Sp ...

  7. Spring读取配置文件,获取bean的几种方式

    Spring读取配置文件,获取bean的几种方式 方法一:在初始化时保存ApplicationContext对象 代码: ApplicationContext ac = new FileSystemX ...

  8. [Config]如何利用ConfigurationSettings.AppSettings.GetValues读取配置文件中多个同Key的value...

    编写者:郑昀@Ultrapower 默认情况下, string[] strArray = System.Configuration.ConfigurationSettings.AppSettings. ...

  9. C++编写Config类读取配置文件

    老外写的一段代码,在Server中编写这个类读取配置文件比较实用 C++代码   //Config.h #pragma once #include <string> #include &l ...

最新文章

  1. 神经网络粒子和物理粒子的一个本质差别
  2. python中判断实例可迭代地几种方式
  3. boost::gil::threshold_truncate用法的测试程序
  4. CodeForce 168 C——Wizards and Trolleybuses
  5. Google的wiki-map也上线了
  6. ubuntu 16.04 更换阿里源
  7. kdj线指标详解与案例探究
  8. vue页面引用echart的词云图
  9. 指纹识别_Android指纹认证教程
  10. 那些年微信开发过的鸡肋功能,及其带给我们的思考
  11. 文科生学python简书_文科生Python教程(一)
  12. 使用Dreamweaver创建一个PHP程序
  13. Apache2.4的安装、配置与常见的问题(Windows)
  14. Sigfox获法国最大一笔VC投资,打造物联网自己的互联网
  15. Tiktok的websocket私信协议详解。
  16. 路飞学城Python-Day31
  17. 服务器系统ghost蓝屏,win7系统ghost安装一半蓝屏的解决方法
  18. shell 脚本练习 | 「题霸」面试必考真题【shell篇】题解
  19. ardruino控制继电器_Arduino 各种模块篇-继电器
  20. [附源码]SSM计算机毕业设计小区物业管理系统论文JAVA

热门文章

  1. leetcode题解200-岛屿数量
  2. redis学习-redis五大数据类型
  3. 虚拟机中的CentOS 7设置固定IP连接最理想的配置
  4. USACO 2006 Open, Problem. The Country Fair 动态规划
  5. Selenium:利用select模块处理下拉框
  6. [转]在Visual Studio 2013/2015中设计UML活动图
  7. BZOJ 1010: [HNOI2008]玩具装箱toy 斜率优化dp
  8. Windows下安装和配置Maven的方法及注意事项
  9. mysql什么是覆盖索引,MySQL中的覆盖索引
  10. python 单链表查找元素_如何在python中一次找到链表的中间元素?