在 Linux 下用 C++ 读取配置文件,常见做法有几种,取决于你使用的配置格式和是否愿意用第三方库。下面按常见程度给你讲清楚。
config.iniip = 127.0.0.1
port = 8080
debug = 1
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <map>
std::map<std::string, std::string> read_config(const std::string& filename) {
std::map<std::string, std::string> config;
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)) {
// 去空格
key.erase(0, key.find_first_not_of(" "));
key.erase(key.find_last_not_of(" ") + 1);
value.erase(0, value.find_first_not_of(" "));
value.erase(value.find_last_not_of(" ") + 1);
config[key] = value;
}
}
return config;
}
int main() {
auto cfg = read_config("config.ini");
std::cout << "ip=" << cfg["ip"] << std::endl;
std::cout << "port=" << cfg["port"] << std::endl;
}
✅ 优点:无依赖、简单
❌ 缺点:不支持 section、类型转换需自己写
[server]
ip = 127.0.0.1
port = 8080
[log]
level = debug
你可以用第三方库:
inih(非常轻量)#include "ini.h"
static int handler(void* user, const char* section,
const char* name, const char* value) {
printf("[%s] %s = %s\n", section, name, value);
return 1;
}
int main() {
ini_parse("config.ini", handler, nullptr);
}
config.json{
"ip": "127.0.0.1",
"port": 8080,
"debug": true
}
#include <nlohmann/json.hpp>
#include <fstream>
using json = nlohmann::json;
int main() {
std::ifstream f("config.json");
json cfg = json::parse(f);
std::cout << cfg["ip"] << std::endl;
std::cout << cfg["port"] << std::endl;
}
✅ 优点:结构清晰、类型安全
❌ 需要第三方库
如果你是写系统服务:
/etc/xxx.conflibconfig#include <libconfig.h++>
libconfig::Config cfg;
cfg.readFile("app.cfg");
std::string ip = cfg.lookup("ip");
| 场景 | 推荐方式 |
|---|---|
| 小工具 | key=value 自己解析 |
| 中大型 C++ 项目 | JSON / inih |
| 系统服务 | libconfig |
| 嵌入式 | inih |
如果你愿意,可以告诉我:
我可以给你直接可用的完整代码模板。