【C++】手搓读写properties文件源码

【C++】手搓读写properties文件源码

    • 参考文章

思路
properties文件实际上就是键值对的一种形式,用等号连接键和值。c++中和键值对最贴切的就是STL中的map了。所以我使用map作为properties的实际内存存储,同时为了方便使用,另外多一个set类型的字段记录所有的key。大致流程为:

1、逐行扫描文件内容;
2、过滤注释(#后面的为注释);
3、根据等号切割key和value;
4、保存key和value到map中;

需求:
1、当key没有值时:可以设定个默认值
2、读取文件时只有KEY没哟默认值会报错,添加一个默认值给该KEY
3、修改KEY的值时并保存到文件中

properties.h 头文件

/**
  ******************************************************************************
  * @file           : properties.h
  * @author         : CircleDBA
  * @mail           : weiyuanquan@kingbase.com.cn
  * @blog           : circle-dba.blog.csdn.net
  * @date           : 24-5-8
  ******************************************************************************
  */


#ifndef KINGBASEMANAGERTOOLS_PROPERTIES_H
#define KINGBASEMANAGERTOOLS_PROPERTIES_H

#include <iostream>
#include <fstream>
#include <map>
#include <string>
#include <algorithm>
#include <sstream>
#include <vector>
#include <set>
#include <filesystem>

using namespace std;

namespace Circle {

    class properties {
    private:
        string config_path;
        map<string, string>* props = nullptr;
        set<string>* keys = nullptr;

        void trim(string& s);
        vector<string> split(const string& str, char pattern);
    public:
        properties();
        virtual ~properties();
        void file(boost::filesystem::path path);
        bool is_exists();
        bool load(std::string defaultValue);
        bool load(){load("None");};
        set<string>* getKeys() const;
        map<string, string>* getProps() const;
        string getValue(const string& key,const string& defaultValue);
        bool setValue(const string& key,const string& Value);
    };

} // Circle

#endif //KINGBASEMANAGERTOOLS_PROPERTIES_H

properties.cpp 文件

/**
  ******************************************************************************
  * @file           : properties.cpp
  * @author         : CircleDBA
  * @mail           : weiyuanquan@kingbase.com.cn
  * @blog           : circle-dba.blog.csdn.net
  * @date           : 24-5-8
  ******************************************************************************
  */


#include "properties.h"

namespace fs = std::filesystem;

Circle::properties::properties() {
    this->props = new map<string, string>();
    this->keys = new set<string>();
}

Circle::properties::~properties() {
    delete props;
    delete keys;

}
//设置配置文件路径
void Circle::properties::file(std::string path){
    this->config_path = path;
}
//判断配置文件是否存在
bool Circle::properties::is_exists(){
    return fs::exists(this->config_path);
}

void Circle::properties::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::properties::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::properties::load(std::string defaultValue = "None"){
    std::ifstream file(this->config_path);
    std::string line;
    while (getline(file, line)) {
        trim(line);
        //去空行
        if (line.empty() || line == "\r" || line[0] == '#')
        {
            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(res[0], res[1]));
        keys->insert(res[0]);
    }
    file.close();
}

set<string>* Circle::properties::getKeys() const {
    return keys;
}

map<string, string>* Circle::properties::getProps() const {
    return this->props;
}

string Circle::properties::getValue(const string& key,const string& defaultValue) {
    if (props->find(key) == props->end())
    {
        return defaultValue;
    }
    string value =this->props->at(key);
    return value;
}

bool Circle::properties::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;
    }

    std::ofstream outFile(this->config_path);
    for (const auto& pair : *props) {
        outFile << pair.first << " = " << pair.second << std::endl;
    }
    return true;
}

example.properties 示例代码

key1 = value1
key3 = value3
key5 = aaa
log.key4 = value4

运行例子:

#include "properties.h"
main(){
	 std::string configPaht = "example.properties"
	 Circle::properties properties;
     properties.file(configPaht);
     //判断配置文件是否存在
     if(properties.is_exists()){
     	//读取配置文件写入props,keys
     	properties.load();
     	//读取键值,如果不存在就返回默认值defaultValue
     	properties.getValue("key5","defaultValue");
     	//设置键值并写入文件
     	properties.setValue("key5","aaa");
     }
}

参考文章

C++读取Properties的工具类

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/603328.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Oopsie从80端口到获取root权限的渗透过程

Oopsie 需要用到的工具burpnmapnc手写代码信息收集 由于是靶场的原因单一没有子站所以收集到ip就可以nmap扫描 拿到IP第一件事就是扫描端口 nmap -T4 -sV -sC -sS 10.129.24.79 -T4:提升扫描速度 -sV&#xff1a;查看详细版本 -sC:使用默认类别的脚本进行扫描 可更换其他类别…

ADC模-数转换原理与实现

1. 今日摸鱼计划 今天来学习一下ADC的原理&#xff0c;然后把ADC给实现 ADC芯片:ADC128S102 视频&#xff1a; 18A_基于SPI接口的ADC芯片功能和接口时序介绍_哔哩哔哩_bilibili 18B_使用线性序列机思路分析SPI接口的ADC芯片接口时序_哔哩哔哩_bilibili 18C_基于线性序列机的S…

“情况不明,对子先行”攻略

掼蛋作为一种策略性极强的游戏&#xff0c;不仅考验牌技&#xff0c;更考验玩家的智慧和策略布局。这里主要介绍一下当牌力不足的时候的普通策略—情况不明&#xff0c;对子先行。 当你的牌力不强&#xff0c;或者牌局情况不明朗时&#xff0c;自己手上有有比较多的对子&#x…

【前端】前端数据本地化的多种实现方式及其优劣对比

前端数据本地化的多种实现方式及其优劣对比 在现代Web开发中&#xff0c;提高页面响应速度和改善用户体验是核心目标之一。数据本地化是其中一种实现方式&#xff0c;它通过在客户端存储数据来减少服务器请求&#xff0c;从而加快数据载入速度和改善用户的体验。本文将介绍前端…

面试大全资料分享-工作无忧

找工作啦 面试大全资料分享 关注公众号 回复 面试大全 即可获取下载链接.

Chromium编译指南2024 Windows11篇-GN 工具生成构建文件(六)

前言 在《Chromium编译指南2024&#xff08;五&#xff09;》我们已经获取了 Chromium 的源代码并且同步了相关的第三方依赖。 现在&#xff0c;我们将进一步学习如何使用 GN 工具生成构建文件&#xff0c;为后续的编译工作做好准备。 1. 使用gn工具生成构建文件 再次在Win…

C#里如何设置输出路径,不要net7.0-windows

官网介绍&#xff1a; 更改生成输出目录 - Visual Studio (Windows) | Microsoft Learn <PropertyGroup> <AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath> <AppendRuntimeIdentifierToOutputPath>false</Appen…

Shell编程之条件语句与case语句

一、条件测试操作 Shell环境根据命令执行后的返回状态值&#xff08;$?&#xff09;来判断是否执行成功&#xff0c;当返回值为0&#xff08;真true&#xff09;时表示成功&#xff0c;返回值为非0值&#xff08;假false&#xff09;时表示失败或异常 test命令 测试表达式是…

FPGA学习笔记(1)——Vivado和HLS

1 Vivado设计 1.1 FPGA基本知识 Xilinx Atrix-7使用6输入LUT结构&#xff08;0-63&#xff09;CLB&#xff1a;可配置逻辑块Slice&#xff1a;每个CLB包含2个Slice(包含查找表LUT和8位寄存器REG)布线池&#xff1a;围绕在CLB周围&#xff0c;衔接FPGA的资源调度I/O块&#xf…

由北京车展想到的,技术红利时代的“重启”

北京车展刚刚落幕&#xff0c;雷军和周鸿祎成为网红&#xff0c;国产品牌站上王座。与此同时&#xff0c;马斯克“光速”访华&#xff0c;FSD酝酿入华再掀新竞争。华为在车展前发布的智驾新品牌“乾崑”&#xff0c;同样在现场广受关注。它们的精彩&#xff0c;让燃油车羡慕。 …

六西格玛备考攻略:无从下手?一文让你豁然开朗

当你决定备考六西格玛时&#xff0c;可能会感到有些无从下手。毕竟&#xff0c;这是一个涉及多个领域和方面的综合性考试&#xff0c;需要掌握的知识点和技能也非常广泛。但是&#xff0c;只要你有一个清晰的学习计划和一些有效的备考方法&#xff0c;就能够顺利地通过考试。以…

STM32F405 FOC 使用Timer 触发 ADC采集

STM32F405 FOC 使用Timer 触发 ADC 1. ADC采集模式2. 高级Timer模式3. ADC1 连续采集3.1 DMA软件触发3.2 DMATIM触发 4. ADC 注入模式采集5. 最终使用方法 1. ADC采集模式 根据STM32F405数据手册&#xff0c;可以看到ADC block diagram&#xff0c;ADC主要有两种触发模式&…

【VUE】el-descriptions 描述列表

Descriptions 描述列表 列表形式展示多个字段。 <el-descriptions title"用户信息"><el-descriptions-item label"用户名">kooriookami</el-descriptions-item><el-descriptions-item label"手机号">18100000000</e…

巨资回流,量子投资热潮再起

一股新的信心和资金浪潮正在席卷量子计算产业。 2023年4月30日&#xff0c;澳大利亚联邦政府和昆士兰州政府宣布共同出资9.4亿澳元&#xff08;约合6.2亿美元&#xff09;&#xff0c;支持美国初创企业PsiQuantum在布里斯班附近建设一台大型量子计算机。这项投资是最新的迹象之…

Linux中动态库的用法及优缺点?怎样制作动态库和静态库?

一、什么是gcc gcc的全称是GNU Compiler Collection&#xff0c;它是一个能够编译多种语言的编译器。最开始gcc是作为C语言的编译器&#xff08;GNU C Compiler&#xff09;&#xff0c;现在除了c语言&#xff0c;还支持C、java、Pascal等语言。gcc支持多种硬件平台. 在 Linux…

Leetcode—706. 设计哈希映射【简单】(constexpr)

2024每日刷题&#xff08;127&#xff09; Leetcode—706. 设计哈希映射 数组实现代码 class MyHashMap { public:MyHashMap() {memset(arr, -1, sizeof(arr));}void put(int key, int value) {arr[key] value;}int get(int key) {if(arr[key] -1) {return -1;} return arr…

可视化:智慧能源解决方案,降本增效,运筹帷幄。

智慧能源可视化解决方案是一种利用先进的技术和工具&#xff0c;将能源数据以直观、可视的方式呈现出来&#xff0c;帮助企业更好地管理能源使用&#xff0c;降低成本&#xff0c;提高效率的解决方案。 以下是一些智慧能源可视化解决方案可以帮助企业降本增效、智连未来的方式&…

【前端】实现快速改变内容大小选择框

简言 简单实现选择框改变内容大小和位置。 内容 这里实现选择框改变内容大小是让内容宽高等于选择框的百分之百&#xff0c;当选择框大小改变时&#xff0c;内容也会响应的改变。 位置则是根据定位实现的。 选择框 选择框就是一个div&#xff0c;然后定位上下左右四条边和…

FastText 算法原理及使用方法

文章目录 1. 前言2. 模型架构2.1 Hierarchical Softmax2.2 n-gram 特征 3. 训练及评估4. 使用5. 参考 1. 前言 FastText 是一个由 Facebook AI Research 在2016年开源的文本分类器&#xff0c;它的设计旨在保持高分类准确度的同时&#xff0c;显著提升训练和预测的速度。 论文…

https证书免费申请

https证书也称SSL证书或是TLS证书&#xff0c;主要是用于网站实现https加密访问。 1、工作原理&#xff1a;HTTPS证书在HTTP协议基础上加入了SSL/TLS协议层&#xff0c;实现数据的加密传输。当用户访问启用HTTPS的网站时&#xff0c;浏览器会与网站服务器建立一个安全连接。这个…
最新文章