程序员求职经验分享与学习资料整理平台

网站首页 > 文章精选 正文

C++ Config.ini读取,使用inih库读取ini文件

balukai 2025-01-10 11:33:56 文章精选 5 ℃

1、github 克隆 inih项目

git clone https://github.com/benhoyt/inih.git

2、开始构建,该项目是meson.build 构建

安装 meson,ninja

pip install meson
pip install ninja

3、编译构建,会在当前目录生成build

meson build

如下图:

4、加载动态库

1、需要将libinih.so,libINIReader.so 拷贝 /usr/lib64;

2、inih.pc,INIReader.pc 两个文件拷贝到如下目录

/usr/lib64/pkgconfig
/usr/share/pkgconfig
/usr/local/lib/pkgconfig
/usr/local/lib64/pkgconfig

3、执行命令ldconfig

4、检查是否配置成功

pkg-config --list-all 
ldconfig -v | grep inih
ldconfig -v | grep INIReader

5、使用inih,INIReader

g++ 编译时添加 -lINIReader -linih

g++ -DWITH_TERARKDB -std=c++17 -o ./test-app1/main main.cpp -lINIReader -linih -lrocksdb -ldl -lzstd -lsnappy -llz4 -lbz2 -lz -u zenfs_filesystem_reg -lzbd

6、代码示例

配置文件

; 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
trillion = 1000000000000 ; Test 64-bit integers

1、main.cpp 代码

不要忘记添加 #include "../cpp/INIReader.h"

// Example that shows simple usage of the INIReader class

#include <iostream>
#include "../cpp/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) << ", unsigned version="
              << reader.GetUnsigned("protocol", "version", -1) << ", trillion="
              << reader.GetInteger64("user", "trillion", -1) << ", unsigned trillion="
              << reader.GetUnsigned64("user", "trillion", -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";
    std::cout << "Has values: user.name=" << reader.HasValue("user", "name")
              << ", user.nose=" << reader.HasValue("user", "nose") << "\n";
    std::cout << "Has sections: user=" << reader.HasSection("user")
              << ", fizz=" << reader.HasSection("fizz") << "\n";
    return 0;
}
最近发表
标签列表