温馨提示×

linux c++怎样读配置文件

小樊
35
2026-10-19 17:30:48
栏目: 编程语言

在 Linux 下用 C++ 读取配置文件,常见做法有几种,取决于你使用的配置格式和是否愿意用第三方库。下面按常见程度给你讲清楚。


一、最简单:自己解析 key=value 格式(推荐入门)

1️⃣ 配置文件示例 config.ini

ip = 127.0.0.1
port = 8080
debug = 1

2️⃣ C++ 读取示例

#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、类型转换需自己写


二、支持 section(INI 格式)

[server]
ip = 127.0.0.1
port = 8080

[log]
level = debug

你可以用第三方库:

✅ 推荐库:inih(非常轻量)

  • 单文件 C/C++
  • GitHub: https://github.com/benhoyt/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);
}

三、JSON 配置文件(现代项目推荐)

配置文件 config.json

{
  "ip": "127.0.0.1",
  "port": 8080,
  "debug": true
}

使用 nlohmann/json(最流行)

#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.conf
  • systemd 环境
  • 可用 libconfig
#include <libconfig.h++>
libconfig::Config cfg;
cfg.readFile("app.cfg");
std::string ip = cfg.lookup("ip");

五、总结建议

场景 推荐方式
小工具 key=value 自己解析
中大型 C++ 项目 JSON / inih
系统服务 libconfig
嵌入式 inih

如果你愿意,可以告诉我:

  • 配置格式(ini / json / xml)
  • 是否允许用第三方库
  • 是否是后台服务

我可以给你直接可用的完整代码模板。

0 踩