【C++】手搓读写ini文件源码
【C++】手搓读写ini文件源码
- 思路
- 需求:
- ini.h
- ini.cpp
- config.conf
- mian.cpp
思路
ini文件是一种系统配置文件,它有特定的格式组成。通常做法,我们读取ini文件并按照ini格式进行解析即可。在c++语言中,提供了模板类的功能,所以我们可以提供一个更通用的模板类来解析ini文件。c++中和键值对最贴切的就是STL中的map了。所以我使用map作为properties的实际内存存储,同时为了方便使用,另外多一个set类型的字段记录所有的key。大致流程为:
1、逐行扫描文件内容;
2、过滤注释(#后面的为注释);
3、根据等号切割key和value;
4、保存section,key和value到文件中;
需求:
1、当key没有值时:可以设定个默认值
2、读取文件时只有KEY没哟默认值会报错,添加一个默认值给该KEY
3、修改KEY的值时并保存到文件中,形成固定格式
ini.h
/********************************************************************************* @file : ini.h* @author : CircleDBA* @mail : weiyuanquan@kingbase.com.cn* @blog : circle-dba.blog.csdn.net* @date : 24-5-8*******************************************************************************/#ifndef KINGBASEMANAGERTOOLS_INI_H
#define KINGBASEMANAGERTOOLS_INI_H#include <iostream>
#include <fstream>
#include <sstream>
#include <map>
#include <string>#include <set>
#include <filesystem>#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/filesystem.hpp>using namespace std;namespace Circle {class ini {protected:string config_path;set<string>* keys = nullptr;map<string, string>* props = nullptr;void trim(string& s);vector<string> split(const string& str, char pattern);private:public:ini();virtual ~ini();void file(boost::filesystem::path path);bool is_exists();bool load(std::string defaultValue);bool load(){return load("None");};set<string>* getKeys() const;map<std::string, string> *const getProps() const;string getValue(const string& key,const string& defaultValue);string setValue(const string& key,const string& Value);bool save();};} // Circle#endif //KINGBASEMANAGERTOOLS_INI_H
ini.cpp
/********************************************************************************* @file : ini.cpp* @author : CircleDBA* @mail : weiyuanquan@kingbase.com.cn* @blog : circle-dba.blog.csdn.net* @date : 24-5-8*******************************************************************************/#include "ini.h"namespace fs = boost::filesystem;namespace Circle {Circle::ini::ini() {this->props = new map<string, string>;this->keys = new set<string>();}Circle::ini::~ini() {delete props;delete keys;}void Circle::ini::file(boost::filesystem::path path){this->config_path = path.string();}bool Circle::ini::is_exists(){return fs::exists(this->config_path);}void Circle::ini::trim(string& s){if (!s.empty()){s.erase(0, s.find_first_not_of(" "));s.erase(s.find_last_not_of(" ") + 1);}}vector<string> Circle::ini::split(const string& str, char pattern){vector<string> res;stringstream input(str);string temp;while (getline(input, temp, pattern)){res.push_back(temp);}return res;}bool Circle::ini::load(std::string defaultValue = "None"){std::ifstream file(this->config_path);std::string line, key, value, section;while (getline(file, line)) {trim(line);//去空行if (line.empty() || line == "\r" || line[0] == '#'){continue;}int s_startpos, s_endpos;if (((s_startpos = line.find("[")) != -1) && ((s_endpos = line.find("]"))) != -1){section = line.substr(s_startpos + 1, s_endpos - 1);continue;}//处理等号后为空的配置vector<string> res = split(line, '=');if (res.size() < 2){res[1] = defaultValue;}int t = res[1].find("#");if (t != string::npos) {res[1].erase(t);}for_each(res.begin(), res.end(), [=](string& s)mutable {trim(s);});props->insert(make_pair(section+"."+res[0],res[1]));keys->insert(section);}file.close();return true;}set<string>* Circle::ini::getKeys() const {return keys;}map<std::string, string> *const Circle::ini::getProps() const {return this->props;}string Circle::ini::getValue(const string& key,const string& defaultValue) {if (props->find(key) == props->end()){return defaultValue;}string value = this->props->at(key);return value;}string Circle::ini::setValue(const string& key,const string& Value) {if (props->find(key) == props->end()){this->props->insert(make_pair(key, Value));}else{props->at(key) = Value;}return this->props->at(key);}bool Circle::ini::save(){std::ofstream outFile(this->config_path);set<string>* keysMap = getKeys();for (std::set<string>::const_iterator it = keysMap->begin(); it != keysMap->end(); ++it) {outFile << "[" << *it << "]" << std::endl;for (const auto &pair: *props) {vector<string> res = split(pair.first,'.');if(res[0] == *it){outFile << res[1] << " = " << pair.second << std::endl;}};}return true;}
} // Circle
config.conf
[group1]
IP = 192.168.30.1
name = group1
port = 7000
[group2]
IP = 192.168.1.101
name = group2
port = 7002
mian.cpp
/********************************************************************************* @file : Application.h* @author : CircleDBA* @mail : weiyuanquan@kingbase.com.cn* @blog : circle-dba.blog.csdn.net* @date : 24-5-6*******************************************************************************/#ifndef KINGBASEMANAGERTOOLS_APPLICATION_H
#define KINGBASEMANAGERTOOLS_APPLICATION_H
#include <iostream>
#include <boost/filesystem.hpp>
#include "src/path/path.h"
#include "src/config/ini.h"namespace Circle {class Application {protected:private:public:boost::filesystem::path RootPath,ConfigPath,DefaultConfigPath;Circle::path* Path;Application() {RootPath = Path->ApplictionPath();ConfigPath = RootPath / "config";DefaultConfigPath = RootPath / "include" / "Application" / "config";boost::filesystem::path config = DefaultConfigPath / "config.conf";std::cout << "--------------------------------> start" << std::endl;Circle::ini ini;ini.file(config);if(ini.is_exists()){ini.load();std::cout << ini.getValue("group1.IP","192.168.30.1") << std::endl;std::cout << ini.setValue("group1.IP","192.168.30.1") << std::endl;ini.save();std::cout << "-------------------------------->for start" << std::endl;map<string, string>* dataMap = ini.getProps();for (const auto &pair : *dataMap) {std::cout << pair.first << "=>" << pair.second <<std::endl;};}std::cout << "--------------------------------> end" << std::endl;}};} // Application#endif //KINGBASEMANAGERTOOLS_APPLICATION_H
相关文章:
【C++】手搓读写ini文件源码
【C】手搓读写ini文件源码 思路需求:ini.hini.cppconfig.confmian.cpp 思路 ini文件是一种系统配置文件,它有特定的格式组成。通常做法,我们读取ini文件并按照ini格式进行解析即可。在c语言中,提供了模板类的功能,所以…...

undolog
undolog回滚段 undolog执行的时间:在执行器操作bufferpool之前。 undolog页...
项目文档分享
Hello , 我是小恒。提前祝福妈妈母亲节快乐 。 本文写一篇初成的项目文档 (不是README.md哈),仅供参考 项目名称 脚本存储网页 项目简介 本项目旨在创建一个网页,用于存储和展示各种命令,用户可以通过粘贴复制命令到…...

【深耕 Python】Quantum Computing 量子计算机(5)量子物理概念(二)
写在前面 往期量子计算机博客: 【深耕 Python】Quantum Computing 量子计算机(1)图像绘制基础 【深耕 Python】Quantum Computing 量子计算机(2)绘制电子运动平面波 【深耕 Python】Quantum Computing 量子计算机&…...
手写Spring5【笔记】
Spring5【笔记】 前言前言推荐Spring5【笔记】1介绍2手写 最后 前言 这是陈旧已久的草稿2022-12-01 23:32:59 这个是刷B站的时候,看到一个手写Spring的课程。 最后我自己好像运行不了,就没写。 现在2024-5-12 22:22:46,发布到[笔记]专栏中…...

2024中国(重庆)机器人展览会8月举办
2024中国(重庆)机器人展览会8月举办 邀请函 主办单位: 中国航空学会 重庆市南岸区人民政府 招商执行单位: 重庆港华展览有限公司 2024中国重庆机器人展会将汇聚机器人全产业链知名企业,世界科技领先的生产制造企业与来自多个国家和地区…...
Apache 开源项目文档中心 (英文 + 中文)
进度:持续更新中。。。 Apache Ambari 2.7.5 Apache Ambari Installation 2.7.5.0 (latest)Apache Ambari Installation 2.7.5.0 中文版 (latest) Apache DolphinScheduler Apache DolphinScheduler 1.2.0 中文版Apache DolphinScheduler 1.2.1 中文版...
蓝桥杯 算法提高 ADV-1164 和谐宿舍 python AC
贪心,二分 同类型题:蓝桥杯 算法提高 ADV-1175 打包 def judge(x):wood 0max_val 0ans_len 0for i in ll:if i > x:return Falseelif max(max_val, i) * (ans_len 1) < x:max_val max(max_val, i)ans_len 1else:wood 1max_val ians_len …...

Dragonfly 拓扑的路由算法
Dragonfly 拓扑的路由算法 1. Dragonfly 上的路由 (1)最小路由(2)非最小路由 2. 评估3. 存在问题 (1)吞吐量限制(2)较高的中间延迟 references Dragonfly 拓扑的路由算法 John Kim, William J. Dally 等人在 2008 年的 ISCA 中提出技术驱动、高度可扩展的 Dragonfly 拓扑。而…...

android基础-服务
同样使用intent来传递服务 oncreate是服务第一次启动调用,onStartCommand是服务每次启动的时候调用,也就是说服务只要启动后就不会调用oncreate方法了。可以在myservice中的任何位置调用stopself方法让服务停止下来。 服务生命周期 前台服务类似于通知会…...
mysql 事物
MySQL中的事务(Transaction)是一个确保数据完整性和一致性的重要概念。它将一组SQL操作捆绑在一起,当作一个单一的工作单元来执行。事务具备以下四个关键特性,即ACID特性: 原子性(Atomicity)&am…...

Unity Shader中获取像素点深度信息
1.顶点着色器中对深度进行计算 v2f vert(appdata v) {v2f o;o.pos UnityObjectToClipPos(v.vertex);o.uv TRANSFORM_TEX(v.uv, _MainTex);o.depth (o.pos.z / o.pos.w 1.0) * 0.5; // Normalize depth to [0, 1]return o; }但是达不到预期,最后返回的值一直大于…...
ROS——Action学习
文章目录 ROS Action概念自定义Action类型参考ROS Action概念 ROS Service会阻塞程序流,程序无法进行其它的工作,有时我们需要同时进行多个任务。 ROS Action可以满足要求,ROS Action提供程序的非阻塞执行。 Action是ROS Node的通信方式之一 Action server 向ROS系统广…...

基于C语言中的类型转换,C++标准创造出了更加可视化的类型转换
目录 前言 一、 C语言中的类型转换 二、为什么C需要四种类型转换 三、C中新增的四种强制类型转换操作符以及它们的应用场景 1.static_cast 2.reinterpret_cast 3.const_cast 4.dynamic_cast 前言 在C语言中,如果赋值运算符左右两侧的类型不同,或者…...
如何创建族表
https://jingyan.baidu.com/article/c275f6bafa5714a23c756768.html...

【UnityRPG游戏制作】Unity_RPG项目_PureMVC框架应用
👨💻个人主页:元宇宙-秩沅 👨💻 hallo 欢迎 点赞👍 收藏⭐ 留言📝 加关注✅! 👨💻 本文由 秩沅 原创 👨💻 收录于专栏:就业…...
并行计算的一些知识点分享--并行系统,并行程序, 并发,并行,分布式
并行计算 核是个啥? 在并行计算中,“核”通常指的是处理器的核心(CPU核心)。每个核心都是一个独立的处理单元,能够执行计算任务。多核处理器指的是拥有多个这样核心的单一物理处理器,这样的设计可以允许多…...
设计模式:访问者模式
访问者模式(Visitor Pattern)是行为设计模式的一种,它使你能够在不修改对象结构的情况下,给对象结构中的每个元素添加新的功能。访问者模式将数据结构和作用于结构上的操作解耦,使得操作集合可相对自由地演化。 核心概…...

vivado Virtex-7 配置存储器器件
Virtex-7 配置存储器器件 下表所示闪存器件支持通过 Vivado 软件对 Virtex -7 器件执行擦除、空白检查、编程和验证等配置操作。 本附录中的表格所列赛灵思系列非易失性存储器将不断保持更新 , 并支持通过 Vivado 软件对其中所列非易失性存储器 进行擦除、…...

检测服务器环境,实现快速部署。适用于CRMEB_PRO/多店
运行效果如图: 最近被好多人问,本来运行的好好的,突然swoole就启动不了了。 本工具为爱发电,如果工具正好解决了您的需求。我会很开心 代码如下: """本脚本为爱发电by:网前雨刮器 """…...
浏览器访问 AWS ECS 上部署的 Docker 容器(监听 80 端口)
✅ 一、ECS 服务配置 Dockerfile 确保监听 80 端口 EXPOSE 80 CMD ["nginx", "-g", "daemon off;"]或 EXPOSE 80 CMD ["python3", "-m", "http.server", "80"]任务定义(Task Definition&…...
Leetcode 3576. Transform Array to All Equal Elements
Leetcode 3576. Transform Array to All Equal Elements 1. 解题思路2. 代码实现 题目链接:3576. Transform Array to All Equal Elements 1. 解题思路 这一题思路上就是分别考察一下是否能将其转化为全1或者全-1数组即可。 至于每一种情况是否可以达到…...

通过Wrangler CLI在worker中创建数据库和表
官方使用文档:Getting started Cloudflare D1 docs 创建数据库 在命令行中执行完成之后,会在本地和远程创建数据库: npx wranglerlatest d1 create prod-d1-tutorial 在cf中就可以看到数据库: 现在,您的Cloudfla…...
【SpringBoot】100、SpringBoot中使用自定义注解+AOP实现参数自动解密
在实际项目中,用户注册、登录、修改密码等操作,都涉及到参数传输安全问题。所以我们需要在前端对账户、密码等敏感信息加密传输,在后端接收到数据后能自动解密。 1、引入依赖 <dependency><groupId>org.springframework.boot</groupId><artifactId...

Cilium动手实验室: 精通之旅---20.Isovalent Enterprise for Cilium: Zero Trust Visibility
Cilium动手实验室: 精通之旅---20.Isovalent Enterprise for Cilium: Zero Trust Visibility 1. 实验室环境1.1 实验室环境1.2 小测试 2. The Endor System2.1 部署应用2.2 检查现有策略 3. Cilium 策略实体3.1 创建 allow-all 网络策略3.2 在 Hubble CLI 中验证网络策略源3.3 …...

Linux-07 ubuntu 的 chrome 启动不了
文章目录 问题原因解决步骤一、卸载旧版chrome二、重新安装chorme三、启动不了,报错如下四、启动不了,解决如下 总结 问题原因 在应用中可以看到chrome,但是打不开(说明:原来的ubuntu系统出问题了,这个是备用的硬盘&a…...
06 Deep learning神经网络编程基础 激活函数 --吴恩达
深度学习激活函数详解 一、核心作用 引入非线性:使神经网络可学习复杂模式控制输出范围:如Sigmoid将输出限制在(0,1)梯度传递:影响反向传播的稳定性二、常见类型及数学表达 Sigmoid σ ( x ) = 1 1 +...
重启Eureka集群中的节点,对已经注册的服务有什么影响
先看答案,如果正确地操作,重启Eureka集群中的节点,对已经注册的服务影响非常小,甚至可以做到无感知。 但如果操作不当,可能会引发短暂的服务发现问题。 下面我们从Eureka的核心工作原理来详细分析这个问题。 Eureka的…...

Selenium常用函数介绍
目录 一,元素定位 1.1 cssSeector 1.2 xpath 二,操作测试对象 三,窗口 3.1 案例 3.2 窗口切换 3.3 窗口大小 3.4 屏幕截图 3.5 关闭窗口 四,弹窗 五,等待 六,导航 七,文件上传 …...
GitHub 趋势日报 (2025年06月06日)
📊 由 TrendForge 系统生成 | 🌐 https://trendforge.devlive.org/ 🌐 本日报中的项目描述已自动翻译为中文 📈 今日获星趋势图 今日获星趋势图 590 cognee 551 onlook 399 project-based-learning 348 build-your-own-x 320 ne…...