记录C++语言中对于项目配置文件的编写及加载配置信息的过程,此处需要撰写三种文件:
configuration.json configuration.h configuration.cpp
对于json文件:
{
"HOST_IP" : 192.168.0.138,
"PORT" : 8030
}
对于h文件:
#ifndef CONFIGURATION_H
#define CONFIGURATION_H
#include <iostream>
#include <string>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
static std::string Host_Ip = "HOST_IP";
static std::string Port = "PORT";
// 加载制定路径的配置文件
json loadConfiguration(std::string fileName);
// 根据给定的json数据,获取制定key的字符串型数值
std::string getConfigString(json js, std::string key);
#endif
对于cpp文件:
#include "configuration.h"
#incldue <iostream>
// 加载制定路径的配置文件
json loadConfiguration(std::string fileName) {
std::ifsteam configFile(filwName);
if (!configFilw.is_open()) {
std::cerr << "Failed to open!" << fileName << std::endl;
return nullptr;
}
json config;
configFile >> config;
return config;
}
// 根据给定的json数据,获取制定key的字符串型数值
std::string getConfigString(json js, std::string key) {
if (js == NULL || key == "") {
return "-1";
}
return js[key];
}
应用代码:
#include "include/configuration.h"
#include <iostream>
#include <string>
······
json config = loadConfiguration("configuration.json");
std::string strHostIp = config["Host_Ip"];
std::string strPort = config["Port"];
······