今天给大家推荐一个基于C/C++语言开发的ini文件解析库:
inih
介绍:
inih是用C语言编写的一个简单的.INI文件解析器。它只有几页代码,它被设计得很小,很简单,所以适合嵌入式系统。它也或多或少兼容Python的ConfigParser风格的.INI文件,包括RFC 822风格的多行语法和名称:name: value (键值对)。
使用:
要使用它,只需给ini_parse()传入一个INI文件名,它将为每个键值对解析的对象调用一个回调函数,回掉函数里会将解析的字符串内容,键值对返回。
特点:使用方便,只需要包含头文件即可使用。支持C、C++。
使用示例:
ini配置文件内容:
; Test config file for ini_example.c and INIReaderTest.cpp [protocol] ; Protocol configuration version=6 ; IPv6 [user] name = Bob Smith ; Spaces around '=' are stripped email = bob@smith.com ; And comments (like this) ignored active = true ; Test a boolean pi = 3.14159 ; Test a floating point number
C语言:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "../ini.h" typedef struct { int version; const char* name; const char* email; } configuration; static int handler(void* user, const char* section, const char* name, const char* value) { configuration* pconfig = (configuration*)user; #define MATCH(s, n) strcmp(section, s) == 0 && strcmp(name, n) == 0 if (MATCH("protocol", "version")) { pconfig->version = atoi(value); } else if (MATCH("user", "name")) { pconfig->name = strdup(value); } else if (MATCH("user", "email")) { pconfig->email = strdup(value); } else { return 0; /* unknown section/name, error */ } return 1; } int main(int argc, char* argv[]) { configuration config; if (ini_parse("test.ini", handler, &config) < 0) { printf("Can't load 'test.ini'\n"); return 1; } printf("Config loaded from 'test.ini': version=%d, name=%s, email=%s\n", config.version, config.name, config.email); return 0; }
C++语言:
#include <iostream> #include "INIReader.h" int main() { INIReader reader("../examples/test.ini"); if (reader.ParseError() < 0) { std::cout << "Can't load 'test.ini'\n"; return 1; } std::cout << "Config loaded from 'test.ini': version=" << reader.GetInteger("protocol", "version", -1) << ", name=" << reader.Get("user", "name", "UNKNOWN") << ", email=" << reader.Get("user", "email", "UNKNOWN") << ", pi=" << reader.GetReal("user", "pi", -1) << ", active=" << reader.GetBoolean("user", "active", true) << "\n"; return 0; }
更多内容请参考作者github.
文章的脚注信息由WordPress的wp-posturl插件自动生成