在 Linux 下用 C++ 做配置文件,常见做法有几种,从简单到专业都有。下面按使用频率给你一个清晰总结,并附示例。
key=value 文本配置文件(最常用 ✅)适合:小型项目、服务程序、工具程序
config.iniip=127.0.0.1
port=8080
debug=true
timeout=30
#include <iostream>
#include <fstream>
#include <sstream>
#include <unordered_map>
std::unordered_map<std::string, std::string> config;
void load_config(const std::string& filename) {
std::ifstream file(filename);
std::string line;
while (std::getline(file, line)) {
if (line.empty() || line[0] == '#') continue;
std::istringstream iss(line);
std::string key, value;
if (std::getline(iss, key, '=') && std::getline(iss, value)) {
config[key] = value;
}
}
}
int main() {
load_config("config.ini");
std::string ip = config["ip"];
int port = std::stoi(config["port"]);
std::cout << "ip=" << ip << ", port=" << port << std::endl;
}
✅ 优点
❌ 缺点
适合:现代 C++ 项目、跨语言配置
config.json{
"ip": "127.0.0.1",
"port": 8080,
"debug": true,
"timeout": 30
}
sudo apt install nlohmann-json3-dev
#include <iostream>
#include <fstream>
#include "nlohmann/json.hpp"
using json = nlohmann::json;
int main() {
std::ifstream file("config.json");
json config;
file >> config;
std::string ip = config["ip"];
int port = config["port"];
std::cout << ip << ":" << port << std::endl;
}
✅ 优点
app.ini[server]
ip=127.0.0.1
port=8080
[log]
level=debug
git clone https://github.com/benhoyt/inih.git
C++ 可直接用,或 C 方式调用。
✅ 优点
config.yamlserver:
ip: 127.0.0.1
port: 8080
yaml-cppsudo apt install libyaml-cpp-dev
✅ 优点
❌ 缺点
很多 Linux 程序这样设计:
./app --config config.json
int main(int argc, char* argv[]) {
std::string config_file = "default.json";
for (int i = 1; i < argc; ++i) {
if (std::string(argv[i]) == "--config") {
config_file = argv[i + 1];
}
}
}
| 场景 | 推荐方式 |
|---|---|
| 小工具 | key=value |
| 服务端程序 | JSON |
| 传统 Linux 程序 | INI |
| 大型系统 | YAML |
Linux C++ 配置文件 = 文本文件 + 解析逻辑
简单用key=value,现代项目用 JSON / YAML
如果你愿意,我可以:
你现在做的是 服务端 / 客户端 / 驱动 / 工具 哪一类?