温馨提示×

Linux C++怎么配置文件

小樊
42
2026-08-16 00:56:44
栏目: 编程语言

在 Linux 下用 C++ 做配置文件,常见做法有几种,从简单到专业都有。下面按使用频率给你一个清晰总结,并附示例。


一、最简单:key=value 文本配置文件(最常用 ✅)

适合:小型项目、服务程序、工具程序

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

ip=127.0.0.1
port=8080
debug=true
timeout=30

2️⃣ C++ 读取示例(自己解析)

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

优点

  • 简单直观
  • 不依赖第三方库

缺点

  • 不支持嵌套、复杂结构

二、JSON 配置文件(推荐 ✅✅)

适合:现代 C++ 项目、跨语言配置

1️⃣ 配置文件 config.json

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

2️⃣ 使用 nlohmann/json(最流行)

安装

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

优点

  • 结构清晰
  • 支持数组、嵌套
  • 工业级常用

三、INI 配置文件(传统但好用)

1️⃣ 配置文件 app.ini

[server]
ip=127.0.0.1
port=8080

[log]
level=debug

2️⃣ 使用 inih(轻量库)

git clone https://github.com/benhoyt/inih.git

C++ 可直接用,或 C 方式调用。

优点

  • 标准 INI 格式
  • 易维护

四、YAML 配置文件(大型项目)

示例 config.yaml

server:
  ip: 127.0.0.1
  port: 8080

常用库

  • yaml-cpp
sudo 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


如果你愿意,我可以:

  • ✅ 给你一个 完整可编译示例
  • ✅ 设计一个 线程安全的配置管理类
  • ✅ 帮你选 最适合你项目的方案

你现在做的是 服务端 / 客户端 / 驱动 / 工具 哪一类?

0