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

读取配置文件在C++中很常见,但标准库不直接支持INI或JSON格式,需要借助第三方库或手动解析。下面介绍两种主流方式:用 inih 读INI,用 nlohmann/json 读JSON,都是轻量、头文件仅需、无依赖的推荐方案。
inih(INI Not Invented Here)是一个极简的C语言INI解析器,C++可直接使用,支持只读模式,无需编译,只需包含头文件。
步骤:
ini.h 和 ini.c(或仅用纯头文件版 ini.hpp,GitHub上有C++封装)INI_USE_STACK 宏未定义(避免栈溢出风险)示例(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 是目前最流行的C++ JSON库,头文件即用,语法直观,支持现代C++特性(如结构体映射)。
步骤:
json.hpp,放入项目目录(或用 vcpkg/conan 安装)#include "json.hpp",使用 nlohmann::json 类型json::parse() 或 json::parse_file() 加载内容示例(config.json):
{
"database": {
"host": "127.0.0.1",
"port": 3306,
"timeout": 5
},
"log": {
"level": "info",
"path": "./logs/app.log"
}
}C++代码(含结构体自动反序列化):
#include "json.hpp"
#include <fstream>
#include <iostream>
#include <string>
using json = nlohmann::json;
struct Config {
struct Database { std::string host; int port; int timeout; };
struct Log { std::string level; std::string path; };
Database database;
Log log;
};
void from_json(const json& j, Config::Database& d) {
d.host = j.value("host", "localhost");
d.port = j.value("port", 3306);
d.timeout = j.value("timeout", 3);
}
void from_json(const json& j, Config::Log& l) {
l.level = j.value("level", "warn");
l.path = j.value("path", "./app.log");
}
void from_json(const json& j, Config& c) {
c.database = j.at("database").get<Config::Database>();
c.log = j.at("log").get<Config::Log>();
}
Config load_json(const std::string& filename) {
std::ifstream f(filename);
try {
json j = json::parse(f);
return j.get<Config>();
} catch (const json::exception& e) {
std::cerr << "JSON parse error: " << e.what() << "\n";
return {};
}
}INI适合简单扁平配置(如桌面工具、嵌入式),人类易读写;JSON适合嵌套结构、跨语言协作(如服务端配置、API响应模拟)。
minIni 或 SimpleIni
j.at("key") 可抛异常,用 j.value("key", default) 更安全argv[0] 解析)基本上就这些。两个库都足够轻、文档全、社区稳,选一个上手快,配好一次就能复用多年。
以上就是C++如何读取配置文件(ini/json)?(方法与示例)的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号