C++读取配置文件推荐使用inih解析INI和nlohmann/json解析JSON:inih轻量无依赖,适合扁平配置;nlohmann/json支持嵌套与结构体映射,适合复杂跨语言场景。

读取配置文件在C++中很常见,但标准库不直接支持INI或JSON格式,需要借助第三方库或手动解析。下面介绍两种主流方式:用 inih 读INI,用 nlohmann/json 读JSON,都是轻量、头文件仅需、无依赖的推荐方案。
用 inih 读取 INI 文件
inih(INI Not Invented Here)是一个极简的C语言INI解析器,C++可直接使用,支持只读模式,无需编译,只需包含头文件。
步骤:
- 下载
ini.h和ini.c(或仅用纯头文件版ini.hpp,GitHub上有C++封装) - 将头文件加入工程,确保
INI_USE_STACK宏未定义(避免栈溢出风险) - 实现回调函数,按节(section)、键(key)、值(value)逐行处理
示例(test.ini):
立即学习“C++免费学习笔记(深入)”;
[database] host = 127.0.0.1 port = 3306 timeout = 5 [log] level = info path = ./logs/app.log
登录后复制
C++代码(使用 inih 的 C++ 封装 ini.hpp):
#include "ini.hpp"
#include <iostream>
#include <string>
struct Config {
std::string db_host = "localhost";
int db_port = 3306;
int db_timeout = 3;
std::string log_level = "warn";
std::string log_path = "./app.log";
};
Config load_ini(const std::string& filename) {
Config cfg;
INIReader reader(filename);
if (reader.ParseError() != 0) {
std::cerr << "Can't load " << filename << "\n";
return cfg;
}
cfg.db_host = reader.Get("database", "host", cfg.db_host);
cfg.db_port = reader.GetInteger("database", "port", cfg.db_port);
cfg.db_timeout = reader.GetInteger("database", "timeout", cfg.db_timeout);
cfg.log_level = reader.Get("log", "level", cfg.log_level);
cfg.log_path = reader.Get("log", "path", cfg.log_path);
return cfg;
}登录后复制
用 nlohmann/json 读取 JSON 文件
nlohmann/json 是目前最流行的C++ JSON库,头文件即用,语法直观,支持现代C++特性(如结构体映射)。
标签: js git json github c语言 app 回调函数 工具 栈 c++ ios stream 配置文件 标准库
还木有评论哦,快来抢沙发吧~