温馨提示×

linux c++怎么读取配置文件

小樊
40
2026-09-29 05:59:32
栏目: 编程语言

在 Linux 下用 C++ 读取配置文件,常见做法有几种,取决于配置文件的格式和你是否愿意用第三方库。下面按“从简单到规范”的方式给你讲。


一、最简单:自定义文本格式(键值对)

示例配置文件 config.ini

ip = 127.0.0.1
port = 8080
name = test

C++ 读取示例

#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;
}

✅ 优点:无依赖
❌ 缺点:不支持嵌套、类型转换需自己写


二、标准做法:INI 文件(推荐)

使用第三方库(轻量)

  • inih(非常流行,单文件)
  • GitHub: https://github.com/benhoyt/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
✅ 代码简洁
✅ 嵌入式/服务器常用


三、JSON 配置(现代 C++ 项目)

使用 nlohmann/json

{
  "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;
}

✅ 类型安全
✅ 可嵌套
❌ 需引入库


四、系统级配置(Linux 特有)

1. 环境变量

#include <cstdlib>
#include <iostream>

int main() {
    const char* ip = std::getenv("APP_IP");
    if (ip) std::cout << ip << std::endl;
}

2. /etc/ 下配置文件

通常配合上面方法读取


五、推荐方案(总结)

场景 推荐方式
简单服务 自定义键值对
多模块配置 inih (INI)
复杂结构 JSON
系统服务 配置文件 + 环境变量

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

  • 配置文件格式(ini / json / xml / 自定义)
  • 是否允许用第三方库
  • 是嵌入式还是服务器程序

我可以给你直接可用的完整示例代码。

0 踩