1. 程式人生 > >C++編寫Config類讀取配置檔案

C++編寫Config類讀取配置檔案

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



C++程式碼  收藏程式碼
  1. // Config.cpp  
  2. #include "Config.h"  
  3. using namespace std;  
  4. Config::Config( string filename, string delimiter,  
  5.                string comment )  
  6.                : m_Delimiter(delimiter), m_Comment(comment)  
  7. {  
  8.     // Construct a Config, getting keys and values from given file  
  9.     std::ifstream in( filename.c_str() );  
  10.     if( !in ) throw File_not_found( filename );   
  11.     in >> (*this);  
  12. }  
  13. Config::Config()  
  14. : m_Delimiter( string(1,'=') ), m_Comment( string(1,'#') )  
  15. {  
  16.     // Construct a Config without a file; empty  
  17. }  
  18. bool Config::KeyExists( const string& key ) const  
  19. {  
  20.     // Indicate whether key is found  
  21.     mapci p = m_Contents.find( key );  
  22.     return ( p != m_Contents.end() );  
  23. }  
  24. /* static */  
  25. void Config::Trim( string& inout_s )  
  26. {  
  27.     // Remove leading and trailing whitespace  
  28.     static const char whitespace[] = " \n\t\v\r\f";  
  29.     inout_s.erase( 0, inout_s.find_first_not_of(whitespace) );  
  30.     inout_s.erase( inout_s.find_last_not_of(whitespace) + 1U );  
  31. }  
  32. std::ostream& operator<<( std::ostream& os, const Config& cf )  
  33. {  
  34.     // Save a Config to os  
  35.     for( Config::mapci p = cf.m_Contents.begin();  
  36.         p != cf.m_Contents.end();  
  37.         ++p )  
  38. 相關推薦

    C++編寫Config讀取配置檔案

    老外寫的一段程式碼,在Server中編寫這個類讀取配置檔案比較實用  C++程式碼   //Config.h   #pragma once   #include <string>   #include <map>   #include <

    C++builder利用GetPrivateProfileString讀取配置檔案

     GetPrivateProfileString配置檔案中經常用到ini檔案,在C++builder或者Delphi中其函式分別為: 寫入.ini檔案:bool WritePrivateProfileString(LPCTSTR lpAppName,LPC

    Properties讀取配置檔案資訊

    一、Java Properties類     Java中有個比較重要的類Properties(Java.util.Properties),主要用於讀取Java的配置檔案,各種語言都有自己所支援的配置檔案,配置檔案中很多變數是經常改變的,這樣做也是為了方便使用者,讓使

    C#使用ConfigurationManager操作配置檔案

    .net1.1中如果需要靈活的操作和讀寫配置檔案並不是十分方便,一般都會在專案中封裝一個配置 檔案管理類來進行讀寫操作。而在.net2.0中使用configurationmanager 和webconfigurationmanager 類可以很好的管理配置檔案,configurationmanager類在s

    C# winForm讀取配置檔案 App.config

    //讀取配置窗體中使用者輸入的配置 string server = txtServer.Text.Trim();string database = txtDatabase.Text.Trim();string uid = txtUid.Text.Trim();string pwd = txtPwd.T

    MySQL-讀取配置檔案的工具與測試

    package JDBCUtil; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.ut

    讀取配置檔案的工具實現

    /** * 讀取配置檔案的工具類 * */ public class ConfigManager { // 第一步:構建私有的靜態的例項 private static ConfigManager configManager; private static Properties pr

    C++讀取配置檔案.txt連線資料庫

    mysql=mysql_init((MYSQL*)0); ifstream file; string path="D:/data.txt"; file.open(path.c_str()); string port1; string url; string name; str

    自定義讀取配置檔案

    #include<iostream> #include<string.h> #include<vector> #include<map> #include<set> #include <fstream> #include<

    Asp.net Core 和讀取配置檔案資訊

    Asp.net Core 和類庫讀取配置檔案資訊 看乾貨請移步至.net core 讀取配置檔案公共類 首先開一個腦洞,Asp.net core 被使用這麼長時間了,但是關於配置檔案(json)的讀取,微軟官方似乎並沒有給出像.net framework讀取web.config那樣簡單且完美。嚴重懷

    在ServletContextListener 的實現中(使用Spring @Value 註解的方式讀取配置檔案、或者注入Spring bean)

    在ServletContextListener 的實現類中 使用Spring @Value 註解的方式讀取配置檔案 我想向ServletContextListener中通過Spring @value 的方法讀取 properties 配置檔案資訊,但是我開始的方法不行 public class MyLi

    讀取配置檔案config.properties的方法

    引入的jar包: 這兩個jar包版本是配套的,建議使用maven 使用的jar版本需要與spring整體版本適應 commons-configuration-1.8.jar commons-lang-2.6.jar(commons-configuration的依賴

    .NET CORE 讀取配置檔案繫結到

    前言,好記性不如爛筆頭 1,NuGet管理器新增 三個引用Microsoft.Extensions.Configuration,Microsoft.Extensions.Configuration.Binder,Microsoft.Extensions.Configurat

    讀取配置檔案 properties工具

    import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import

    Spring Cloud入門教程-Config Server從github 遠端讀取配置檔案

          接上一篇文章,這裡記錄一下Config Server從github 遠端讀取配置檔案。         Spring cloud Config支援從遠端Git倉庫讀取配置檔案,即 Config Server可以不從本地的倉庫讀取,而是從遠端Git倉庫讀取。這

    springboot 專案框架搭建(三):工具讀取配置檔案

    一.原因     編寫一個服務類的工具類,想做成一個靈活的配置,各種唯一code想從配置檔案中讀取,便有了這個坑。  二.使用@value獲取值為null,     這是因為這個工具類沒有交給spring boot 來管理,導致每次都是new 一個新的,所以每次取出來的

    【java】 一個讀取配置檔案

    /** * <p>Title:InitConfig.java</p> * <p>Description:</p> * @author songrongkai * @date 2018年7月29日 * @version 1.0 */ p

    自己編寫讀取配置檔案的資訊的方法

    結果: 程式碼: public static void main(String[] args) { //自己編寫的讀取配置檔案的方法 InputStream inputStream = FtpConfig.class.getResourceAsStream("/

    Spring Cloud學習筆記(十)-配置中心Config元件從GitHub讀取配置檔案

    說明:本文僅作為本人學習<<深入理解Spring Cloud與微服務構建>>一書的學習筆記,所有程式碼案例及文字描述均參考該書,不足之處,請留言指正,不勝感激. 一.為什麼要使用Config元件?   我覺得主要有兩點,方便配置統一

    c++:讀取配置檔案

    namespace fs = boost::filesystem; fs::path objPath = strFilePath; //  strFilePath--目錄   objPath/=strFileName;// strFileName--檔名 if(o