C/C++跨平台INI文件解析库:iniparser

使用c语言实现的跨平台INI文件解析库,下载地址:https://github.com/ndevilla/iniparser
解析库很小巧,1500行代码,4个文件,跨平台,没有依赖项目,使用 -ansi -pedantic C89 编译
使用起来很方便,官方例子如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "iniparser.h"

void create_example_ini_file(void);
int  parse_ini_file(char * ini_name);

int main(int argc, char * argv[])
{
    int     status ;

    if (argc<2) {    
        /*创建示例ini文件,并解析*/   
        create_example_ini_file();
        status = parse_ini_file("example.ini");
    } else {
        status = parse_ini_file(argv[1]);
    }
    return status ;
}

void create_example_ini_file(void)
{
    FILE    *   ini ;

    if ((ini=fopen("example.ini", "w"))==NULL) {
        fprintf(stderr, "iniparser: cannot create example.ini\n");
        return ;
    }

    fprintf(ini,
    "#\n"
    "# This is an example of ini file\n"
    "#\n"
    "\n"
    "[Pizza]\n"
    "\n"
    "Ham = yes ;\n"
    "Mushrooms = TRUE ;\n"
    "Capres = 0 ;\n"
    "Cheese = Non ;\n"
    "\n"
    "\n"
    "[Wine]\n"
    "\n"
    "Grape = Cabernet Sauvignon ;\n"
    "Year = 1989 ;\n"
    "Country = Spain ;\n"
    "Alcohol = 12.5 ;\n"
    "\n");
    fclose(ini);
}


int parse_ini_file(char * ini_name)
{
    dictionary  *   ini ;

    /* Some temporary variables to hold query results */
    int             b ;
    int             i ;
    double          d ;
    const char  *   s ;
    /*创建解析库句柄,所有数据存储在ini里面,所有操作也需要这个句柄*/
    ini = iniparser_load(ini_name);
    if (ini==NULL) {
        fprintf(stderr, "cannot parse file: %s\n", ini_name);
        return -1 ;
    }
    iniparser_dump(ini, stderr);

    /* Get pizza attributes */
    printf("Pizza:\n");
    /*pizza是所属段明ham是段内参数名,iniparser_getboolean会将返回值转化成bool值*/
    b = iniparser_getboolean(ini, "pizza:ham", -1);
    printf("Ham: [%d]\n", b);
    b = iniparser_getboolean(ini, "pizza:mushrooms", -1);
    printf("Mushrooms: [%d]\n", b);
    b = iniparser_getboolean(ini, "pizza:capres", -1);
    printf("Capres: [%d]\n", b);
    b = iniparser_getboolean(ini, "pizza:cheese", -1);
    printf("Cheese: [%d]\n", b);

    /* Get wine attributes */
    printf("Wine:\n");
    /*获取string类型的值*/
    s = iniparser_getstring(ini, "wine:grape", NULL);
    printf("Grape: [%s]\n", s ? s : "UNDEF");

    /*获取int类型的值*/
    i = iniparser_getint(ini, "wine:year", -1);
    printf("Year: [%d]\n", i);

    s = iniparser_getstring(ini, "wine:country", NULL);
    printf("Country: [%s]\n", s ? s : "UNDEF");
    /*获取double类型的值*/
    d = iniparser_getdouble(ini, "wine:alcohol", -1.0);
    printf("Alcohol: [%g]\n", d);
    /*用完之后不要忘记释放句柄,不然会有内存泄露*/
    iniparser_freedict(ini);
    return 0 ;
}   

你可能感兴趣的:(C语言,ini)