平常的ini配置文件只能读取,但是这个库不光可以读取、写入配置项,还能给配置项写注释。只有一个hpp头文件,不需要编译,支持C++11及之后版本。
MIT license,配置INI文件就像喝水一样简单。
一、库下载
https://github.com/dujingning/inicpp 或者 https://gitee.com/dujingning/inicpp
二、库使用
- git clone
git clone https://github.com/dujingning/inicpp.git
包含 inicpp.hpp
,声明类 inicpp::iniReader
,然后就可以随意使用了.
1.读取INI文件示例
#include "inicpp.hpp"
int main()
{
// Load and parse the INI file.
inicpp::iniReader _ini("config.ini");
std::cout << _ini["rtsp"]["port"] << std::endl;
}
2.写示例
#include "inicpp.hpp"
int main()
{
// Load and parse the INI file.
inicpp::iniReader _ini("config.ini");
_ini.modify("rtsp","port","554");
std::cout << _ini["rtsp"]["port"] << std::endl;
}
* 3.添加注释
#include "inicpp.hpp"
int main()
{
// Load and parse the INI file.
inicpp::iniReader _ini("config.ini");
_ini.modify("rtsp","port","554","this is the listen port for rtsp server");
std::cout << _ini["rtsp"]["port"] << std::endl;
}
* 4.toString()、toInt()、toDouble()
#include "inicpp.hpp"
int main()
{
// Load and parse the INI file.
inicpp::iniReader _ini("config.ini");
_ini.modify("rtsp","port","554","this is the listen port for rtsp server");
std::cout << _ini["rtsp"]["port"] << std::endl;
// Convert to string, default is string
std::string http_port_s = _ini["http"].toString("port");
std::cout << "to string:\thttp.port = " << http_port_s << std::endl;
// Convert to double
double http_port_d = _ini["http"].toDouble("port");
std::cout << "to double:\thttp.port = " << http_port_d << std::endl;
// Convert to int
int http_port_i = _ini["http"].toInt("port");
std::cout << "to int:\t\thttp.port = " << http_port_i << std::endl;
}
* 5.完整示例:example/main.cpp
.
编译demo到example目录下make一下就好了: example/Makefile
.
没有make命令,只需要执行: g++ -I../ -std=c++11 main.cpp -o iniExample
6.linux下使用demo的完整示例:example/main.cpp
编译
example/main.cpp
[jn@jn inicpp]$ ls example inicpp.hpp LICENSE README.md [jn@jn inicpp]$ cd example/ [jn@jn example]$ make g++ -I../ -std=c++11 main.cpp -o iniExample [jn@jn example]$ ls iniExample main.cpp Makefile
运行
iniExample
[jn@jn example]$ ./iniExample get rtsp port:555 to string: rtsp.port = 554 to string: math.PI = 3.1415926 to string: math.PI = 3.1415926 to double: math.PI = 3.1415926 to int: math.PI = 3 to wstring: other.desc= 你好,世界 [jn@jn example]$
生成
config.ini
```bash
[jn@jn example]$ cat config.ini
;no section test:add comment later.
noSection=yes
key0=noSectionAndComment
key1=noSectionAndComment
key2=noSectionAndComment
[head]
;thanks for your using inicpp project.
title=inicpp
;Permissive license for open-source software distribution.
license=MIT
[rtsp]
;this is the listen ip for rtsp server.
port=554
ip=127.0.0.1
[math]
;This is pi in mathematics.
PI=3.1415926
[other]
;this test for std::wstring. comment it.
desc=你好,世界
[jn@jn example]$
```