Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2706639
  • 博文数量: 505
  • 博客积分: 1552
  • 博客等级: 上尉
  • 技术积分: 2514
  • 用 户 组: 普通用户
  • 注册时间: 2007-09-23 18:24
文章分类

全部博文(505)

文章存档

2019年(12)

2018年(15)

2017年(1)

2016年(17)

2015年(14)

2014年(93)

2013年(233)

2012年(108)

2011年(1)

2009年(11)

分类: C/C++

2015-09-18 15:27:21

原文地址:GKeyFile生成配置文件 作者:jcodeer

还记得Windows使用的配置文件吗?看看boot.ini文件内容

[boot loader]
timeout=30
default=multi(0)disk(0)rdisk(0)partition(2)\WINDOWS
[operating systems]
multi(0)disk(0)rdisk(0)partition(2)\WINDOWS="Windows Server 2003, Standard" /fastdetect /NoExecute=OptOut
C:\wubildr.mbr = "Ubuntu"

Linux中提供了功能更为强大的KeyValue数据格式,可用于生成更为灵活的配置文件,下面的代码实例演示了使用GKeyFile生成配置文件,本例代码使用了字符串,布尔值,整型值,双精度值和字符串列表等数据类型,将其写入配置文件中。

#include
#include

int main(int argc,char** argv){
    GKeyFile* config = g_key_file_new();
    gsize length = 0;
    
#define STARUP "STARTUP"
#define PATH "PATH"

    g_key_file_set_value(config,STARUP,"x","300");
    g_key_file_set_string(config,STARUP,"y","600");
    g_key_file_set_boolean(config,STARUP,"center",TRUE);

    GTimeVal now;
    g_get_current_time(&now);
    g_key_file_set_integer(config,STARUP,"timestamp",now.tv_sec);
    
    GRand* r = g_rand_new();
    g_key_file_set_double(config,STARUP,"random",g_rand_double(r));

    const char* const search_path[] = { "/bin","/sbin","/usr/bin","/usr/local/bin","/home/jcodeer/bin"};
    g_key_file_set_string_list(config,PATH,"bin_path",search_path,5);

    gchar* content = g_key_file_to_data(config,&length,NULL);
    g_print("%s\n",content);

    FILE* fp = fopen("./019.ini","w");
    if(fp == NULL) return -1;
    fwrite(content,1,length,fp);
    fclose(fp);

#undef STARUP
#undef PATH

    g_key_file_free(config);

    return 0;
}

生成的INI配置文件内容为:

[STARTUP]
x=300
y=600
center=true
timestamp=1314432584
random=0.78204092288815774

[PATH]
bin_path=/bin;/sbin;/usr/bin;/usr/local/bin;/home/jcodeer/bin;

阅读(1931) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~