glib 学习笔记1,读取程序配置文件

glib 学习笔记,读取程序配置文件
转载请联系作者:fanyuanmail@126.com
有时在写一个程序时经常会从一个配置文件中读取一系列的参数,在度bluez代码时发现了一个非常好的方法。
这个方法基于glib-2.0,例如要从名为main.conf中读取里面的配置值。
offmode = NoScan
pagetimeout = 8192
age = 26

  1 [General]
  2
  3 # List of plugins that should not be loaded on bluetoothd startup
  4 #DisablePlugins = network,input
  5
  6 # Default adaper name
  7 # %h - substituted for hostname
  8 # %d - substituted for adapter id
  9 Name = %h-%d:
 10
 11 # Default device class. Only the major and minor device class bits are
 12 # considered
 13 Class = 0x000100
 14
 15 # How long to stay in discoverable mode before going back to non-discoverable
 16 # The value is in seconds. Default is 180, i.e. 3 minutes.
 17 # 0 = disable timer, i.e. stay discoverable forever
 18 DiscoverableTimeout = 0
 19
 20 # Use some other page timeout than the controller default one
 21 # (16384 = 10 seconds)
 22 PageTimeout = 8192
 23
 24 # Behaviour for Adapter.SetProperty("mode", "off")
 25 # Possible values: "DevDown", "NoScan" (default)
 26 OffMode = NoScan
 27
 28 # Discover scheduler interval used in Adapter.DiscoverDevices
 29 # The value is in seconds. Defaults is 0 to use controller scheduler
 30 DiscoverSchedulerInterval = 0
 31 [test]
 32 age=26
 
 
#include <glib.h>
static GKeyFile *load_config(const char *file)
{
        GError *err = NULL;
        GKeyFile *keyfile;
        keyfile = g_key_file_new();
        g_key_file_set_list_separator(keyfile, ',');
        if (!g_key_file_load_from_file(keyfile, file, 0, &err)) {
                error("Parsing %s failed: %s", file, err->message);
                g_error_free(err);
                g_key_file_free(keyfile);
                return NULL;
        }
        return keyfile;
}

int main(int argc, int **argv)
{
        char* str;
        int val1,val2;
        GError* err = NULL;
        GKeyFile* keyfile;
        keyfile = load_config("main.conf");
        str = g_key_file_get_string(keyfile,"General","OffMode",&err);
        if (err) {
                printf("%s",err->message);
                g_clear_error(&err);
        }
        val1 = g_key_file_get_integer(keyfile,"General","PageTimeout",&err);
        if (err) {
                printf("%s",err->message);
                g_clear_error(&err);
        }
        val2 = g_key_file_get_integer(keyfile,"test","age",&err);
        if (err) {
                printf("%s",err->message);
  g_clear_error(&err);
        }
        printf("offmode = %s/n",str);
        printf("pagetimeout = %d/n",val1);
        printf("age = %d/n",val2);
        return 0;
}
gcc -g `pkg-config --cflags --libs glib-2.0 gthread-2.0` glib_parser.c -o glib_parser

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值