C/C++ 读取配置文件的几种方式

文章介绍了如何使用protobuf读取配置文件,定义并编译.proto格式配置,以及如何结合gflags管理C++代码中的可配置选项。同时展示了json格式的配置文件示例和在C代码中加载配置文件的过程。
摘要由CSDN通过智能技术生成

1. protobuf

  • 将配置信息读取到string流中
/**
 * @brief 将配置文件读取到string流中
 * 
 * @param file_name :配置文件名称
 * @param content: 读取后的string配置信息流
 * @return true :成功读取
 * @return false:打开文件失败
 */
bool GetContent(const std::string &file_name, std::string *content) {
  // 打开文件流
  std::ifstream fin(file_name);
  if (!fin) {
    return false;
  }
  // 获取流缓冲区 
  std::stringstream str_stream;
  str_stream << fin.rdbuf();
  *content = str_stream.str();
  return true;
}
  • 创建proto格式配置文件(dag_config.proto)
message DAGConfig {
    enum SubnodeType {
        SUBNODE_IN = 1; 
        SUBNODE_OUT = 2;
        SUBNODE_NORMAL = 3;
    };

    // Subnode instance.
    message Subnode {
        required int32 id = 1;
        required string name = 2;
        // node private data.节点私有数据
        optional string reserve = 3;
        optional SubnodeType type = 4 [default = SUBNODE_NORMAL];
    };

    message SubnodeConfig {
        repeated Subnode subnodes = 1;
    };

    message Event {
        required int32 id = 1;
        optional string name = 2;
    };

    message Edge {
        required int32 id = 1;
        required int32 from_node = 2;
        required int32 to_node = 3;
        repeated Event events = 4;
    };

    message EdgeConfig {
        repeated Edge edges = 1;
    }

    message SharedData {
        required int32 id = 1;
        required string name = 2;
    };

    message SharedDataConfig {
        repeated SharedData datas = 1;
    }

    required SubnodeConfig subnode_config = 1;
    required EdgeConfig edge_config = 2;
    required SharedDataConfig data_config = 3;
};
  • 将proto文件编译成.cc和.h文件
  • 使用protobuf的序列化进行配置文件解析
  DAGConfig dag_config;
  string content;
  // 获取内容
  if (!GetContent(dag_config_path, &content)) {
    return false;
  }
  // 解析字符串:使用protobuf的序列化进行配置文件解析,将解析结果放置在dag_config中
  if (!TextFormat::ParseFromString(content, &dag_config)) {
    return false;
  }

2. opencv

3. json

4. gflags

  • 在代码中设置待配置变量(alg_fusConfig.hpp)
#ifndef INTERFACE_FUS_CONFIG_H
#define INTERFACE_FUS_CONFIG_H
#include <gflags/gflags.h>
DEFINE_bool(use_dataAcquisition, false,"Whether to use data acquisition");// FLAGS_use_dataAcquisition
DEFINE_bool(use_ydutool, false,"Whether to use ydutools");// FLAGS_use_ydutool
DEFINE_bool(use_aiCarport, true,"Whether to receive visual parking Spaces");// FLAGS_use_aiCarport
DEFINE_bool(use_ultrasonic, true,"Whether to use ultrasonic radar");// FLAGS_use_ultrasonic


// 输出打印
DEFINE_bool(use_debugPtintf, false,"Whether to use ultrasonic radar"); // FLAGS_use_debugPtintf
DEFINE_bool(ptintf_fusCarportList, false,"Whether to use ultrasonic radar"); // FLAGS_ptintf_fusCarportList
DEFINE_bool(ptintf_fusSelectedCarport, false,"Whether to use ultrasonic radar"); // FLAGS_ptintf_fusSelectedCarport
// 输入打印
DEFINE_bool(ptintf_location, false,"Whether to use ultrasonic radar"); // FLAGS_ptintf_location
DEFINE_bool(ptintf_decision, false,"Whether to use ultrasonic radar"); // FLAGS_ptintf_decision
DEFINE_bool(ptintf_carSpace, false,"Whether to use ultrasonic radar"); // FLAGS_ptintf_carSpace
DEFINE_bool(ptintf_userCarSpace, false,"Whether to use ultrasonic radar"); // FLAGS_ptintf_userCarSpace
DEFINE_bool(ptintf_selectedCarport, false,"Whether to use ultrasonic radar"); // FLAGS_ptintf_selectedCarport
DEFINE_bool(ptintf_ultrarRadar, false,"Whether to use ultrasonic radar"); // FLAGS_ptintf_ultrarRadar
DEFINE_bool(ptintf_fapa, false,"Whether to use ultrasonic radar"); // FLAGS_ptintf_fapa
DEFINE_bool(ptintf_vehicle, false,"Whether to use ultrasonic radar"); // FLAGS_ptintf_vehicle
#endif
  • 创建配置文件(config.conf)
## 数据采集
--use_dataAcquisition=false
--use_ydutool=false
--use_aiCarport=true
--use_ultrasonic=true


## 输出打印
--use_debugPtintf=false
--ptintf_fusCarportList=false
--ptintf_fusSelectedCarport=false

## 输入打印
--ptintf_location=false
--ptintf_decision=false
--ptintf_carSpace=false
--ptintf_userCarSpace=false
--ptintf_selectedCarport=false
--ptintf_ultrarRadar=false
--ptintf_fapa=false
--ptintf_vehicle=false
  • 在C代码中加载配置文件
	// 配置文件所在路径
	std::string config_file = "/ota/SW1.0.06/modules/fusion_carport/config/config.conf";
    if( fusCarportLog::CheckPath(config_file) == 1)// 判断配置文件存不存在
    {
        // 生成ParseCommandLineFlags 的参数支持的数据类型
        std::string stingArray[2];
        stingArray[0] = "fusion_carport";// 一般设置为进程名称,可以是任意字符,ParseCommandLineFlags函数要求一定需要设置
        stingArray[1] = "--flagfile=";
        stingArray[1] = stingArray[1] + config_file;
        int numStrings = sizeof(stingArray) / sizeof(stingArray[0]);
        char* charPtrArray[numStrings];
        for (std::size_t i = 0; i < numStrings; ++i) {
            charPtrArray[i] = new char[stingArray[i].length() + 1];
            std::strcpy(charPtrArray[i], stingArray[i].c_str());
         }
        auto pArgv = &charPtrArray[0];
        gflags::ParseCommandLineFlags(&numStrings, &pArgv, true);

        for (std::size_t i = 0; i < numStrings; ++i) {
            delete[] charPtrArray[i];
        }
    }else{
        printf( "\n-->%s配置文件不存在\n",config_file.c_str());
    }
   

    printf( "\n FLAGS_use_dataAcquisition=%d\n \
                FLAGS_use_ydutool=%d\n \
                FLAGS_use_aiCarport=%d\n \
                FLAGS_use_ultrasonic=%d\n \
                FLAGS_use_debugPtintf=%d\n \
                FLAGS_ptintf_fusCarportList=%d\n \
                FLAGS_ptintf_fusSelectedCarport=%d\n \
                FLAGS_ptintf_location=%d\n \
                FLAGS_ptintf_decision=%d\n \
                FLAGS_ptintf_carSpace=%d\n \
                FLAGS_ptintf_userCarSpace=%d\n \
                FLAGS_ptintf_selectedCarport=%d\n \
                FLAGS_ptintf_ultrarRadar=%d\n \
                FLAGS_ptintf_fapa=%d\n \
                FLAGS_ptintf_vehicle=%d\n \
                ",FLAGS_use_dataAcquisition,FLAGS_use_ydutool,FLAGS_use_aiCarport,FLAGS_use_ultrasonic,FLAGS_use_debugPtintf, \
                FLAGS_ptintf_fusCarportList,FLAGS_ptintf_fusSelectedCarport,FLAGS_ptintf_location,FLAGS_ptintf_decision, \
                FLAGS_ptintf_carSpace, FLAGS_ptintf_userCarSpace,FLAGS_ptintf_selectedCarport,FLAGS_ptintf_ultrarRadar,FLAGS_ptintf_fapa, \
                FLAGS_ptintf_vehicle);

5. YAML

#include <iostream>
#include <fstream>
#include <yaml-cpp/yaml.h>

bool LoadExtrinsic(const std::string &file_path, Eigen::Affine3d *extrinsic) {
  try {
    YAML::Node config = YAML::LoadFile(file_path);
    if (!config["transform"]) {
      return false;
    }
    if (config["transform"]["translation"] && config["transform"]["rotation"]) {
      double tx = config["transform"]["translation"]["x"].as<double>();
      double ty = config["transform"]["translation"]["y"].as<double>();
      double tz = config["transform"]["translation"]["z"].as<double>();

      double qx = config["transform"]["rotation"]["x"].as<double>();
      double qy = config["transform"]["rotation"]["y"].as<double>();
      double qz = config["transform"]["rotation"]["z"].as<double>();
      double qw = config["transform"]["rotation"]["w"].as<double>();
      *extrinsic =
          Eigen::Translation3d(tx, ty, tz) * Eigen::Quaterniond(qw, qx, qy, qz);
    }
  } catch (const YAML::Exception &e) {
    AERROR << "load extrinsics: " << file_path
           << " failed! error: " << e.what();
    return false;
  }
  return true;
}

int main() {
    try {
        // 加载YAML文件
        YAML::Node config = YAML::LoadFile("config.yaml");
 
        // 读取键值
        std::string key = config["key"].as<std::string>();
        int value = config["value"].as<int>();
 
        // 输出读取的内容
        std::cout << "Key: " << key << ", Value: " << value << std::endl;
    } catch (const std::exception& e) {
        std::cerr << "Exception: " << e.what() << std::endl;
    }
 
    return 0;
}

config.yaml 配置文件

cheader:
  seq: 0
  frame_id: ego_car
  stamp:
    secs: 0
    nsecs: 0
child_frame_id: avm_camera
transform:
  rotation:
    x: 0.0
    y: 0.0
    z: -0.7071068
    w: 0.7071068
  translation:
    x: 0.0
    y: 0.0
    z: 0.0
# 以下坐标基于以车辆后轴中心为原点,x向右的拇指,y向上食指,z指向天空的中指,
# 组成的右手坐标系,且为相对坐标系,非全局坐标系。单位mm
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

听雨听风眠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值