在 Linux 下用 C++ 读取配置文件,常见做法有几种,取决于配置文件的格式和你是否愿意用第三方库。下面按“从简单到规范”的方式给你讲。
config.iniip = 127.0.0.1
port = 8080
name = test
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <map>
std::map<std::string, std::string> readConfig(const std::string& file) {
std::map<std::string, std::string> config;
std::ifstream infile(file);
std::string line;
while (std::getline(infile, 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;
}
}
return config;
}
int main() {
auto cfg = readConfig("config.ini");
std::cout << "ip: " << cfg["ip"] << std::endl;
std::cout << "port: " << cfg["port"] << std::endl;
}
✅ 优点:无依赖
❌ 缺点:不支持嵌套、类型转换需自己写
inih(非常流行,单文件)#include "ini.h"
static int handler(void* user, const char* section, const char* name, const char* value) {
printf("section=%s name=%s value=%s\n", section, name, value);
return 1;
}
int main() {
ini_parse("config.ini", handler, nullptr);
}
✅ 支持 section
✅ 代码简洁
✅ 嵌入式/服务器常用
{
"ip": "127.0.0.1",
"port": 8080
}
#include <iostream>
#include <fstream>
#include <nlohmann/json.hpp>
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;
}
✅ 类型安全
✅ 可嵌套
❌ 需引入库
#include <cstdlib>
#include <iostream>
int main() {
const char* ip = std::getenv("APP_IP");
if (ip) std::cout << ip << std::endl;
}
/etc/ 下配置文件通常配合上面方法读取
| 场景 | 推荐方式 |
|---|---|
| 简单服务 | 自定义键值对 |
| 多模块配置 | inih (INI) |
| 复杂结构 | JSON |
| 系统服务 | 配置文件 + 环境变量 |
如果你愿意,可以告诉我:
我可以给你直接可用的完整示例代码。