C/C++ 配置文件库

返回我的作品 Download

几乎完整的程序或者软件, 都有配置信息, 一般保存在文件中. C/C++ 语言的项目一般使用 .ini 文件作为配置文件. ini 文件和成熟的库供使用, 但缺点很明显, 很难表达父子关系, 因为配置信息应该是一根树 - 配置树.

著名的Web Server Lighttpd 使用 LEMON 来解析配置文件. 有些软件还使用 Lua/Python 等脚本语言来做配置管理. 但很多时候没有这个必要. 配置信息只要是一根树即可.

基于这个考虑, 我开发了 C/C++ 的配置管理库, 可用来做程序/软件的配置模块.

Configurations should be in the form of tree, that's what I started from. In many cases, XML/JSON, even script languages like Lua/Python are not necessary. This project develop a C/C++ library that reads configuration files which grammar uses TAB to indicate parent-child relation. I may say, it is Pythonic. The source code is quit simple and small, hope it helps you, enjoy it.

示例

类Python语法配置文件示例:

# this is a comment

author : ideawu
	url: http://www.ideawu.net

proxy :
	php =
		host = 127.0.0.1
		port = 8088
	py :
		host = 127.0.0.1
		port = 8080

cgi =
	pl = /usr/bin/perl

C语言应用程序读取配置文件示例:

#include <stdio.h>
#include "config.h"

int main(int argc, char **argv){
	struct config *cfg, *c;

	cfg = cfg_load_file("cfg_test.conf");
	if(!cfg){
		return 0;
	}

	printf("\n");
	printf("proxy.php.host = %s\n", cfg_getstr(cfg, "proxy.php.host"));
	printf("proxy.php.port = %d\n", cfg_getnum(cfg, "proxy.php.port"));
	printf("cgi.pl = %s\n", cfg_getstr(cfg, "cgi.pl"));
	printf("\n");

	c = cfg_get(cfg, "author");
	printf("author: %s\n", cfg_str(c));
	printf("url: %s\n", cfg_getstr(c, "url"));
	printf("\n");

	cfg_free(cfg);
	return 0;
}