(转)C++编写Config类读取配置文件

独家解读:简单又强大的配置文件 Config 读写类 一、引言在项目过程中,难免会需要一个方便的配置文件读写类,它可以像游戏的存档文件一样,记录着我们当前项目的配置信息,以至于方便我们每次初始化运行的时候可以从这个配置文件读取上一次的配置信息,当然也可以在程序运行过程中记录用户的配置设置信息。我们理想中的这个配置文件读写类,它要有以下这些方法:1. 支持读入一个指定配置文件的能力2. 支持随时加入一个配置项的能力3. 足够强大,能够写入各种数据结构的配 阅读详情

老外写的一段代码,在Server中编写这个类读取配置文件比较实用

C++代码
  1. //Config.h   
  2. #pragma once   
  3.   
  4. #include <string>   
  5. #include <map>   
  6. #include <iostream>   
  7. #include <fstream>   
  8. #include <sstream>   
  9.   
  10.   
  11. /*  
  12. * /brief Generic configuration Class  
  13. *  
  14. */   
  15. class  Config {  
  16.     // Data   
  17. protected :  
  18.     std::string m_Delimiter;  //!< separator between key and value   
  19.     std::string m_Comment;    //!< separator between value and comments   
  20.     std::map<std::string,std::string> m_Contents;  //!< extracted keys and values   
  21.   
  22.     typedef  std::map<std::string,std::string>::iterator mapi;  
  23.     typedef  std::map<std::string,std::string>::const_iterator mapci;  
  24.     // Methods   
  25. public :  
  26.   
  27.     Config( std::string filename,std::string delimiter = "=" ,std::string comment =  "#"  );  
  28.     Config();  
  29.     template < class  T> T Read(  const  std::string& in_key )  const ;   //!<Search for key and read value or optional default value, call as read<T>   
  30.     template < class  T> T Read(  const  std::string& in_key,  const  T& in_value )  const ;  
  31.     template < class  T>  bool  ReadInto( T& out_var,  const  std::string& in_key )  const ;  
  32.     template < class  T>  
  33.     bool  ReadInto( T& out_var,  const  std::string& in_key,  const  T& in_value )  const ;  
  34.     bool  FileExist(std::string filename);  
  35.     void  ReadFile(std::string filename,std::string delimiter =  "=" ,std::string comment =  "#"  );  
  36.   
  37.     // Check whether key exists in configuration   
  38.     bool  KeyExists(  const  std::string& in_key )  const ;  
  39.   
  40.     // Modify keys and values   
  41.     template < class  T>  void  Add(  const  std::string& in_key,  const  T& in_value );  
  42.     void  Remove(  const  std::string& in_key );  
  43.   
  44.     // Check or change configuration syntax   
  45.     std::string GetDelimiter() const  {  return  m_Delimiter; }  
  46.     std::string GetComment() const  {  return  m_Comment; }  
  47.     std::string SetDelimiter( const  std::string& in_s )  
  48.     { std::string old = m_Delimiter;  m_Delimiter = in_s;  return  old; }    
  49.     std::string SetComment( const  std::string& in_s )  
  50.     { std::string old = m_Comment;  m_Comment =  in_s;  return  old; }  
  51.   
  52.     // Write or read configuration   
  53.     friend  std::ostream& operator<<( std::ostream& os,  const  Config& cf );  
  54.     friend  std::istream& operator>>( std::istream& is, Config& cf );  
  55.   
  56. protected :  
  57.     template < class  T>  static  std::string T_as_string(  const  T& t );  
  58.     template < class  T>  static  T string_as_T(  const  std::string& s );  
  59.     static   void  Trim( std::string& inout_s );  
  60.   
  61.   
  62.     // Exception types   
  63. public :  
  64.     struct  File_not_found {  
  65.         std::string filename;  
  66.         File_not_found( const  std::string& filename_ = std::string() )  
  67.             : filename(filename_) {} };  
  68.         struct  Key_not_found {   // thrown only by T read(key) variant of read()   
  69.             std::string key;  
  70.             Key_not_found( const  std::string& key_ = std::string() )  
  71.                 : key(key_) {} };  
  72. };  
  73.   
  74.   
  75. /* static */   
  76. template < class  T>  
  77. std::string Config::T_as_string( const  T& t )  
  78. {  
  79.     // Convert from a T to a string   
  80.     // Type T must support << operator   
  81.     std::ostringstream ost;  
  82.     ost << t;  
  83.     return  ost.str();  
  84. }  
  85.   
  86.   
  87. /* static */   
  88. template < class  T>  
  89. T Config::string_as_T( const  std::string& s )  
  90. {  
  91.     // Convert from a string to a T   
  92.     // Type T must support >> operator   
  93.     T t;  
  94.     std::istringstream ist(s);  
  95.     ist >> t;  
  96.     return  t;  
  97. }  
  98.   
  99.   
  100. /* static */   
  101. template <>  
  102. inline  std::string Config::string_as_T<std::string>(  const  std::string& s )  
  103. {  
  104.     // Convert from a string to a string   
  105.     // In other words, do nothing   
  106.     return  s;  
  107. }  
  108.   
  109.   
  110. /* static */   
  111. template <>  
  112. inline   bool  Config::string_as_T< bool >(  const  std::string& s )  
  113. {  
  114.     // Convert from a string to a bool   
  115.     // Interpret "false", "F", "no", "n", "0" as false   
  116.     // Interpret "true", "T", "yes", "y", "1", "-1", or anything else as true   
  117.     bool  b =  true ;  
  118.     std::string sup = s;  
  119.     for ( std::string::iterator p = sup.begin(); p != sup.end(); ++p )  
  120.         *p = toupper(*p);  // make string all caps   
  121.     if ( sup==std::string( "FALSE" ) || sup==std::string( "F" ) ||  
  122.         sup==std::string("NO" ) || sup==std::string( "N" ) ||  
  123.         sup==std::string("0" ) || sup==std::string( "NONE" ) )  
  124.         b = false ;  
  125.     return  b;  
  126. }  
  127.   
  128.   
  129. template < class  T>  
  130. T Config::Read( const  std::string& key )  const   
  131. {  
  132.     // Read the value corresponding to key   
  133.     mapci p = m_Contents.find(key);  
  134.     if ( p == m_Contents.end() )  throw  Key_not_found(key);  
  135.     return  string_as_T<T>( p->second );  
  136. }  
  137.   
  138.   
  139. template < class  T>  
  140. T Config::Read( const  std::string& key,  const  T& value )  const   
  141. {  
  142.     // Return the value corresponding to key or given default value   
  143.     // if key is not found   
  144.     mapci p = m_Contents.find(key);  
  145.     if ( p == m_Contents.end() )  return  value;  
  146.     return  string_as_T<T>( p->second );  
  147. }  
  148.   
  149.   
  150. template < class  T>  
  151. bool  Config::ReadInto( T& var,  const  std::string& key )  const   
  152. {  
  153.     // Get the value corresponding to key and store in var   
  154.     // Return true if key is found   
  155.     // Otherwise leave var untouched   
  156.     mapci p = m_Contents.find(key);  
  157.     bool  found = ( p != m_Contents.end() );  
  158.     if ( found ) var = string_as_T<T>( p->second );  
  159.     return  found;  
  160. }  
  161.   
  162.   
  163. template < class  T>  
  164. bool  Config::ReadInto( T& var,  const  std::string& key,  const  T& value )  const   
  165. {  
  166.     // Get the value corresponding to key and store in var   
  167.     // Return true if key is found   
  168.     // Otherwise set var to given default   
  169.     mapci p = m_Contents.find(key);  
  170.     bool  found = ( p != m_Contents.end() );  
  171.     if ( found )  
  172.         var = string_as_T<T>( p->second );  
  173.     else   
  174.         var = value;  
  175.     return  found;  
  176. }  
  177.   
  178.   
  179. template < class  T>  
  180. void  Config::Add(  const  std::string& in_key,  const  T& value )  
  181. {  
  182.     // Add a key with given value   
  183.     std::string v = T_as_string( value );  
  184.     std::string key=in_key;  
  185.     trim(key);  
  186.     trim(v);  
  187.     m_Contents[key] = v;  
  188.     return ;  
  189. }  



C++代码
  1. // Config.cpp   
  2.   
  3. #include "Config.h"   
  4.   
  5. using   namespace  std;  
  6.   
  7.   
  8. Config::Config( string filename, string delimiter,  
  9.                string comment )  
  10.                : m_Delimiter(delimiter), m_Comment(comment)  
  11. {  
  12.     // Construct a Config, getting keys and values from given file   
  13.   
  14.     std::ifstream in( filename.c_str() );  
  15.   
  16.     if ( !in )  throw  File_not_found( filename );   
  17.   
  18.     in >> (*this );  
  19. }  
  20.   
  21.   
  22. Config::Config()  
  23. : m_Delimiter( string(1,'=' ) ), m_Comment( string(1, '#' ) )  
  24. {  
  25.     // Construct a Config without a file; empty   
  26. }  
  27.   
  28.   
  29.   
  30. bool  Config::KeyExists(  const  string& key )  const   
  31. {  
  32.     // Indicate whether key is found   
  33.     mapci p = m_Contents.find( key );  
  34.     return  ( p != m_Contents.end() );  
  35. }  
  36.   
  37.   
  38. /* static */   
  39. void  Config::Trim( string& inout_s )  
  40. {  
  41.     // Remove leading and trailing whitespace   
  42.     static   const   char  whitespace[] =  " /n/t/v/r/f" ;  
  43.     inout_s.erase( 0, inout_s.find_first_not_of(whitespace) );  
  44.     inout_s.erase( inout_s.find_last_not_of(whitespace) + 1U );  
  45. }  
  46.   
  47.   
  48. std::ostream& operator<<( std::ostream& os, const  Config& cf )  
  49. {  
  50.     // Save a Config to os   
  51.     for ( Config::mapci p = cf.m_Contents.begin();  
  52.         p != cf.m_Contents.end();  
  53.         ++p )  
  54.     {  
  55.         os << p->first << " "  << cf.m_Delimiter <<  " " ;  
  56.         os << p->second << std::endl;  
  57.     }  
  58.     return  os;  
  59. }  
  60.   
  61. void  Config::Remove(  const  string& key )  
  62. {  
  63.     // Remove key and its value   
  64.     m_Contents.erase( m_Contents.find( key ) );  
  65.     return ;  
  66. }  
  67.   
  68. std::istream& operator>>( std::istream& is, Config& cf )  
  69. {  
  70.     // Load a Config from is   
  71.     // Read in keys and values, keeping internal whitespace   
  72.     typedef  string::size_type pos;  
  73.     const  string& delim  = cf.m_Delimiter;   // separator   
  74.     const  string& comm   = cf.m_Comment;     // comment   
  75.     const  pos skip = delim.length();         // length of separator   
  76.   
  77.     string nextline = "" ;   // might need to read ahead to see where value ends   
  78.   
  79.     while ( is || nextline.length() > 0 )  
  80.     {  
  81.         // Read an entire line at a time   
  82.         string line;  
  83.         if ( nextline.length() > 0 )  
  84.         {  
  85.             line = nextline;  // we read ahead; use it now   
  86.             nextline = "" ;  
  87.         }  
  88.         else   
  89.         {  
  90.             std::getline( is, line );  
  91.         }  
  92.   
  93.         // Ignore comments   
  94.         line = line.substr( 0, line.find(comm) );  
  95.   
  96.         // Parse the line if it contains a delimiter   
  97.         pos delimPos = line.find( delim );  
  98.         if ( delimPos < string::npos )  
  99.         {  
  100.             // Extract the key   
  101.             string key = line.substr( 0, delimPos );  
  102.             line.replace( 0, delimPos+skip, ""  );  
  103.   
  104.             // See if value continues on the next line   
  105.             // Stop at blank line, next line with a key, end of stream,   
  106.             // or end of file sentry   
  107.             bool  terminate =  false ;  
  108.             while ( !terminate && is )  
  109.             {  
  110.                 std::getline( is, nextline );  
  111.                 terminate = true ;  
  112.   
  113.                 string nlcopy = nextline;  
  114.                 Config::Trim(nlcopy);  
  115.                 if ( nlcopy ==  ""  )  continue ;  
  116.   
  117.                 nextline = nextline.substr( 0, nextline.find(comm) );  
  118.                 if ( nextline.find(delim) != string::npos )  
  119.                     continue ;  
  120.   
  121.                 nlcopy = nextline;  
  122.                 Config::Trim(nlcopy);  
  123.                 if ( nlcopy !=  ""  ) line +=  "/n" ;  
  124.                 line += nextline;  
  125.                 terminate = false ;  
  126.             }  
  127.   
  128.             // Store key and value   
  129.             Config::Trim(key);  
  130.             Config::Trim(line);  
  131.             cf.m_Contents[key] = line;  // overwrites if key is repeated   
  132.         }  
  133.     }  
  134.   
  135.     return  is;  
  136. }  
  137. bool  Config::FileExist(std::string filename)  
  138. {  
  139.     bool  exist=  false ;  
  140.     std::ifstream in( filename.c_str() );  
  141.     if ( in )   
  142.         exist = true ;  
  143.     return  exist;  
  144. }  
  145.   
  146. void  Config::ReadFile( string filename, string delimiter,  
  147.                       string comment )  
  148. {  
  149.     m_Delimiter = delimiter;  
  150.     m_Comment = comment;  
  151.     std::ifstream in( filename.c_str() );  
  152.   
  153.     if ( !in )  throw  File_not_found( filename );   
  154.   
  155.     in >> (*this );  
  156. }  


C++代码
  1. //main.cpp   
  2. #include "Config.h"   
  3. int  main()  
  4. {  
  5.     int  port;  
  6.     std::string ipAddress;  
  7.     std::string username;  
  8.     std::string password;  
  9.     const   char  ConfigFile[]=  "config.txt" ;   
  10.     Config configSettings(ConfigFile);  
  11.       
  12.     port = configSettings.Read("port" , 0);  
  13.     ipAddress = configSettings.Read("ipAddress" , ipAddress);  
  14.     username = configSettings.Read("username" , username);  
  15.     password = configSettings.Read("password" , password);  
  16.     std::cout<<"port:" <<port<<std::endl;  
  17.     std::cout<<"ipAddress:" <<ipAddress<<std::endl;  
  18.     std::cout<<"username:" <<username<<std::endl;  
  19.     std::cout<<"password:" <<password<<std::endl;  
  20.       
  21.     return  0;  
  22. }  



config.txt的文件内容:
ipAddress=10.10.90.125
port=3001
username=mark
password=2d2df5a


编译运行输出:
port:3001
ipAddress:10.10.90.125
username:mark
password:2d2df5a

 

这个类还有很多其他的方法,可以调用试试。

 

转载出处: http://cooker.javaeye.com/blog/777455

C++ 读取配置文件的Config类 目录目的Config类代码调用 目的 读取配置文件中的参数及参数值到全局变量中, 我的配置文件示例如下 [MapModel-sim] resolution = 0.1 free_acc_val = 50 obstacle_acc_val = 100 time_diff_threshold = 0.01 ground_lower_threshold = -0.2 ground_upper_threshold = 0.2 obstacle_lower_threshold = -0.05 obstacle_upp 阅读详情

相关推荐

文件读取Config类

前言:写一个负责参数读取的类Config,能够只更改default.yaml内容即可,无需在程序内部更改。 获取相机参数: myslam::Config::setParameterFile("default.yaml"); double fx=myslam::Config::get<double> ("Camera.fx"); 直接调用类中成员函数,需要static静态成员...

try_again_later的博客 764

深入理解C++中的配置文件处理(Config)及其应用场景

深入理解C++中的配置文件处理(Config)及其应用场景

qq_46017342的博客 6118

C++ ini配置文件的格式及读写操作

C++ ini配置文件的格式及读写操作 1 为什么要使用ini或者其它(例如xml,json)配置文件? 如果我们程序没有任何配置文件时,这样的程序对外是全封闭的,一旦程序需要修改一些参数必须要修改程序代码本身并重新编译,这样很不好,所以要用配置文件,让程序发布后还能根据需要进行必要的配置;配置文件有很多如INI配置文件,XML配置文件,还有就是可以使用系统注册表等。注意:ini的后缀名也不一定是".ini"也可以是".cfg",".conf ”或者是".txt"。因为ini文件实质就是txt文本文件。 2

weixin_44517656的博客 1万+

c++读取conf文件

c++格式化读取conf conf文件的结构 [OUTPUT] OutputPath = ./output HpackDecompress = false 1.思考选用什么数据结构(容器选型) ​ 第一阶段:我想的是直接用string,所有操作对string ​ 第二阶段:使用map ​ 第三阶段:使用multimap 因为key存在重复 2.预先处理文件,让存储更加方便 初始化文件,要解决两个问题:1.删除注释行,即#行 2. 删除空行 参考代码: ​ 去掉空行(连接忘了) #include<i

qq_43718336的博客 2468

c++实现逐行读取配置文件写入内存的示例

不解析配置内容,只读取文件内容,剪去注释和首尾空格后写入缓存: vector 中。供其他方法使用。代码是在做一个MFC小工具时写的。 ReadProtocol.h 代码如下:/*** 从文件中 读取 protocol 的内容 写入缓存* 供外部方法使用* Alex Liu, 2014*/ #pragma once #include #include #include #include using namespace std; #define MAX_FILEPATH 512 #define COMMENT_FLG ‘#’#

ESP32+micro-ROS机器人开发实战:轻量级ROS2嵌入式集成

ROS2是现代机器人软件栈的核心框架,其基于DDS的分布式通信与QoS保障能力为多节点协同提供基础支撑;而micro-ROS作为专为微控制器优化的ROS2兼容中间件,解决了资源受限设备(如ESP32)接入ROS2生态的关键难题。其通过分层架构将DDS通信下沉至上位机Agent,使MCU仅需运行轻量Client,大幅降低内存开销(实测<180KB)并保留标准ROS2接口语义。该方案广泛应用于教育机器人、移动底盘、传感器节点等嵌入式场景,尤其适合基于ESP-IDF开发的Wi-Fi/BLE物联网机器人系统。本文以

weixin_29025501的博客 398

C++简单读取配置文件config源码

允许配置中文,注意GBK和utf8字符集转换,默认GBK,配置文件编码为ANSI,要使用utf8,需要设置system("chcp 65001");# 关键字符:# //;cout

mfkdzjp9的专栏 1152

S型速度曲线C程序实现

S型速度曲线C语言程序实现 前言 S型曲线相较于梯形速度曲线具有运行更加平稳的特点,S型曲线共有八种运行情况,感兴趣可以查阅相关文献 代码段 #include <stdio.h> #include <math.h> #define FP64 double int main(void) { /**************************** 定义相关变量(需要映射到PLC寄存器才能进行监控) ***********************/ FP6

LSX312441548的博客 8390

C++编写Config类读取配置文件

头文件: //Config.h #pragma once #include <string> #include <map> #include <iostream> #include <fstream> #include <sstream> /* * \brief Generic configuration Class */ class Config { // Data protected: st...

shigzhu的专栏 1976

Cursor Pro版保姆级开通教程:绕过7天试用,支付宝一步搞定(附地区报错解决方案)

本文详细介绍了Cursor Pro版的订阅流程,包括支付宝支付步骤和解决区域报错的实用方案。针对开发者常见的网络问题和云服务器配置需求,提供了从本地环境调整到云端部署的完整指南,帮助用户高效解锁Pro版的代码补全、私有代码库等核心功能。

weixin_28710999的博客 2087

Matlab2024a安装教程

点击【下一步】。8.选择解压后的【MATLAB R2024a(64bit)】文件夹中【Crack】文件夹下的【licese.lic】,点击【打开】。

qq_64359046的博客 4794

Linux C++实现配置文件读写

文件名:test.data。

xiaoqixiaoguai的博客 1233

初识Classic AUTOSAR开发工具链

在过去,软件和硬件之间具有很强的耦合性,阻碍了软件组件在不同硬件平台上的可移植性和重用性。而AUTOSAR作为汽车电子行业的标准,提供标准的软件接口定义,工程师可以根据需求将软件组件分配到汽车的ECU中,实现标准软件组件的可重用性。

怿星科技的博客 8092

[转]C++编写Config类读取配置文件

C++代码 //Config.h #pragmaonce #include<string> #include<map> #include<iostream> #include<fstream> #include<sstream> /*...

weixin_33802505的博客 192

CentOS Stream 9中安装MySQL的详细步骤

本文详细介绍了在CentOS Stream 9系统中如何进行MySQL的在线安装、离线安装以及忘记密码的恢复操作。通过阅读本文,您将能够了解并掌握在CentOS Stream 9上安装MySQL的步骤,以及在遇到忘记密码的情况下的解决方案。

小白典的博客 7257

Chamfer Loss

ChamferLoss是一种常用于3D点云(pointcloud)处理的损失函数,特别是在点云生成和对齐任务中。它的目的是度量两个点集之间的相似度,特别是在点云重建、配准或生成等任务中,常用于优化模型使得生成的点云更接近真实的点云。

夜空中明亮的星的专栏 455

【c++基础】C++编写Config类读取配置文件

前言 系统程序一般需要读取参数文件,看到一个很好的Config类记录在此。 头文件Config.h //Config.h //re: https://blog.youkuaiyun.com/David_xtd/article/details/9320549 #pragma once #include <string> #include <map&gt...

weixin_30372371的博客 638

华为od 面试八股文_Spring_03_含答案

控制反转IOC是一个很大的概念,可以用不同的方式来实现。其主要实现方式有两种:依赖注入和依赖查找依赖注入;

MISAYAONE的博客 2336

C++编写Config类&ROS动态参数总结

文章目录1.C++编写Config类1.1Config的头文件1.2Config的cpp文件1.3调用Config的类读取txt2.ROS中的Config动态参数2.1动态参数编写2.2动态参数生成2.3调用动态参数 1.C++编写Config类 1.1Config的头文件 //Config.h #pragma once #include <string> #incl...

蒋成的博客 1808

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

C++读取配置文件

想项目开发中终归会用到配置文件,方便改服务器IP端口这些 这个代码适合Key-Value键值对类型的配置文件,我的配置文件是这样的 这份代码我也是拷贝的,然后稍微改造了一下

A cyclist amateur photographer 5736

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

上一篇: (转载)C++中枚举与字符串相互转换
下一篇: (转)C++中枚举与字符串相互转换
berkshirman
博客等级 码龄19年 41粉丝 41原创
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值