libConfuse 使用说明

【前言】
  libconfuse 是一个用 C 实现配置文件解析器库,授权的 ISC 许可的条件下,它支持段(列表)和值(字符串,整数,浮点数,布尔值或其他部分),以及一些其他功能(如单/双引号字符串,环境变量扩展,功能嵌套include语句)。它可以添加配置文件的能力,使用简单的 API 使程序读取配置文件非常容易。


原文:http://www.nongnu.org/confuse/tutorial-html/index.html
作者:Martin Hedenfalk
libConfuse下载:https://github.com/martinh/libconfuse
以往版本下载:http://download.savannah.gnu.org/releases/confuse/
手册:http://www.nongnu.org/confuse/manual/index.html


1. 通过一个实例来介绍 libConfuse

考虑下面这个例子:

#include <stdio.h>

int main(void)
{
    printf("Hello, World!\n");
    return 0;
}

这个例子足够简单,但现在我们想扩展这个程序以便于它可以问候其他人。可能我们只想问候邻居,而不是全世界呢。我们可以使用 libConfuse 让用户决定将要问候谁。

#include <stdio.h>
#include <confuse.h>

int main(void)
{
    cfg_opt_t opts[] =
    {
        CFG_STR("target", "World", CFGF_NONE),
        CFG_END()
    };
    cfg_t *cfg;

    cfg = cfg_init(opts, CFGF_NONE);
    if(cfg_parse(cfg, "hello.conf") == CFG_PARSE_ERROR)
        return 1;

    printf("Hello, %s!\n", cfg_getstr(cfg, "target"));

    cfg_free(cfg);
    return 0;
}

All programs using libConfuse must first include the confuse.h header file. This is done on line 2.

On line 6 - 10, the options that should be recognized are defined in an array of cfg_opt_t structs. This is passed to the cfg_init function on line 13. The resulting cfg_t context is used by cfg_parse(), which reads the configuration file “hello.conf”. When reading the configuration file, only options defined in the array of options passed to cfg_init() are recognized.

The friendly greeting is now replaced with a parameter read from the configuration file. The value of the target option is retrieved with cfg_getstr(cfg, “target”).

Lets take a look at the configuration file hello.conf:

# this is the configuration file for the hello program

target = "Neighbour"

Here, the target option is set to the string value “Neighbour”. What if the configuration file was empty or didn’t exist? Then the default value for the target option would be used. When we initialized our options, the second parameter to the CFG_STR() macro specified the default value. Thus, if no target option was specified in the configuration file, the hello program would have printed the standard greeting “Hello, World”.

1.1. 环境变量

What else can we do in the configuration file? We can set the value to an environment variable:

target = ${USER}

This results in the hello program greeting the user who runs it. On some systems, the USER variable might not be available, so we want to specify a default value in those cases:

target = ${USER:-User}

Now, if the USER environment variable is unset, the string “User” will be used instead.

2. 其他选项类型

Of course, not only strings can be specified in the configuration file. libConfuse can parse strings, integers, booleans and floating point values. These are the fundamental values, and they are all also available as lists. We’ll talk more about lists in the next chapter.

The macros used to initialize a string, integer, boolean and a float is, respectively, CFG_STR(), CFG_INT(), CFG_BOOL(), CFG_FLOAT() and CFG_PTR(). All macros take three parameters: the name of the option, a default value and flags. To retrieve the values, use cfg_getstr(), cfg_getint(), cfg_getbool(), cfg_getfloat() or cfg_getptr(), respectively.

Let’s introduce an integer option that tells us how many times to print the greeting:

#include <stdio.h>
#include <confuse.h>

int main(void)
{
    cfg_opt_t opts[] =
    {
        CFG_STR("target", "World", CFGF_NONE),
        CFG_INT("repeat", 1, CFGF_NONE),
        CFG_END()
    };
    cfg_t *cfg;
    int repeat;

    cfg = cfg_init(opts, CFGF_NONE);
    if(cfg_parse(cfg, "hello.conf") == CFG_PARSE_ERROR)
        return 1;

    repeat = cfg_getint(cfg, "repeat");
    while(repeat--)
        printf("Hello, %s!\n", cfg_getstr(cfg, "target"));

    cfg_free(cfg);
    return 0;
}

Here we have used the CFG_INT() macro to initialize an integer option named “repeat”. The default value is 1 as in the standard greeting. The value is retrieved with cfg_getint().

But, wait a moment, what if the user specified a negative value for “repeat”? Or a too large positive value? libConfuse can handle that with a so-called validating callback. We’ll come back to this problem later on, but we will first take a look at lists.

3. 介绍 lists

4. 使用 sections

5. 从内部缓冲区中解析

6. 使回调函数生效

6.1. 安装回调函数

7. Value parsing callback

8. 函数

8.1. 预定义函数

9. 保存配置文件

9.1. Altering the printing of certain options


(未完待续)

在 Linux 平台上,可以使用类似于 INI 文件的配置文件格式,例如 JSON 或 YAML。针对这样的文件格式,可以使用相应的解析库来读取和写入配置文件。 对于使用 INI 格式的配置文件,可以使用一些库来替代 Windows 平台上的 GetPrivateProfileString 函数。例如,可以使用 libconfuse 库,在 Ubuntu 上使用以下命令安装: ``` sudo apt-get install libconfuse-dev ``` 然后可以使用以下代码来读取配置文件中的值: ```c #include <stdio.h> #include <confuse.h> int main(void) { cfg_t *cfg = cfg_init(); cfg_parse(cfg, "config.cfg"); const char *value = cfg_getstr(cfg, "section.key"); printf("Value: %s\n", value); cfg_free(cfg); return 0; } ``` 其中,"config.cfg" 是配置文件的路径,"section.key" 是要读取的键的名称。此外,还要确保在编译时链接 libconfuse 库。 另外,还可以使用类似于 Glib 的库来读取 INI 格式的配置文件。例如,可以使用以下代码: ```c #include <stdio.h> #include <glib.h> int main(void) { GKeyFile *keyfile = g_key_file_new(); GError *error = NULL; if (!g_key_file_load_from_file(keyfile, "config.ini", G_KEY_FILE_NONE, &error)) { g_error("Failed to load config file: %s", error->message); } gchar *value = g_key_file_get_string(keyfile, "section", "key", &error); printf("Value: %s\n", value); g_free(value); g_key_file_free(keyfile); return 0; } ``` 其中,"config.ini" 是配置文件的路径,"section" 和 "key" 分别是要读取的节和键的名称。此外,还要确保在编译时链接 Glib 库。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值