zoukankan      html  css  js  c++  java
  • 开源函数之1.ini_parse详解

    移植ini解析源码

    要使用ini, 需要先#include "ini.h",我们查看ini.h的头文件介绍如下:可以看到源码的github地址https://github.com/benhoyt/inih

     用git clone https://github.com/benhoyt/inih.git ,下载源码。

     

     

    编写代码test.c:

    #include <stdio.h>
    #include "ini.h"
    #include <string.h>
    typedef struct _SAMPLE_INI_CFG_S { char name[100]; int bus_id; int age; char name2[100]; int bus_id2; int age2; } SAMPLE_INI_CFG_S; static int parse_handler(void *user, const char *section, const char *name, const char *value) { SAMPLE_INI_CFG_S *cfg = (SAMPLE_INI_CFG_S *)user; if (strcmp(section, "person1") == 0) { if (strcmp(name, "name") == 0) { strcpy(cfg->name, value); } else if (strcmp(name, "bus_id") == 0) { cfg->bus_id = atoi(value); } else if (strcmp(name, "age") == 0) { cfg->age = atoi(value); } else { /* unknown section/name */ } } else if (strcmp(section, "person2") == 0) { if (strcmp(name, "name") == 0) { strcpy(cfg->name2, value); } else if (strcmp(name, "bus_id") == 0) { cfg->bus_id2 = atoi(value); } else if (strcmp(name, "age") == 0) { cfg->age2 = atoi(value); } else { /* unknown section/name */ } } else { /* unknown section/name */ } return 1; } int main(int argc, char **argv) { SAMPLE_INI_CFG_S ini_cfg; int ret = ini_parse("./sensor_cfg.ini", parse_handler, &ini_cfg); if (ret > 0) { printf("Parse err in %d line. ", ret); return ret; } if (ret == 0) { printf("Parse incomplete, use default cfg ./sensor_cfg.ini "); printf("%s, %d, %d ", ini_cfg.name, ini_cfg.bus_id, ini_cfg.age); printf("%s, %d, %d ", ini_cfg.name2, ini_cfg.bus_id2, ini_cfg.age2); } return 0; }

     ini配置文件sensor_cfg.ini.

    编译代码:

    Gcc test.c ini.c

    运行代码:

     

    手工制造ini语法错误,测试结果如下:

  • 相关阅读:
    springcloud2.0 添加配置中心遇到的坑
    redis 字符串和集合操作
    Linux
    流畅的python 符合python风格的对象
    流畅的python 对象引用 可变性和垃圾回收
    流畅的python 闭包
    流畅的python 使用一等函数实现设计模式
    互联网协议入门
    流畅的python 字典和集合
    流畅的python python数据模型
  • 原文地址:https://www.cnblogs.com/fuzidage/p/14858971.html
Copyright © 2011-2022 走看看