Advertisement
Guest User

Untitled

a guest
Nov 26th, 2015
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.75 KB | None | 0 0
  1. #ifndef CONFIGMANAGER_H
  2. #define CONFIGMANAGER_H
  3.  
  4. #include "FileManager.h"
  5.  
  6. #include <boost\lexical_cast.hpp>
  7. #include <boost\regex.hpp>
  8.  
  9. #define CONFIGS_DIRECTORY "configs"
  10.  
  11. enum EConfigErrorType
  12. {
  13.     CONFIG_NO_ERROR = 0,
  14.     CONFIG_ERROR_OPEN = 1,
  15.     CONFIG_ERROR_NOT_FOUND = 2,
  16.     CONFIG_ERROR_SYNTAX = 3
  17. };
  18.  
  19. class ConfigManager : public ManagerBase
  20. {
  21. public:
  22.     ConfigManager() {};
  23.     ~ConfigManager() {};
  24.  
  25.     void init(const std::string& name);
  26.     void terminate();
  27.    
  28.     template<typename T>
  29.     T readValue(const std::string& key)
  30.     {
  31.         std::string line = m_file->searchString(key);
  32.         if (line.empty())
  33.         {
  34.             m_lastError = CONFIG_ERROR_NOT_FOUND;
  35.             return T();
  36.         }
  37.  
  38.         boost::smatch match;
  39.         if (!boost::regex_search(line, match, boost::regex(key + "=\"(.*)\"")))
  40.         {
  41.             m_lastError = CONFIG_ERROR_SYNTAX;
  42.             return T();
  43.         }
  44.  
  45.         m_lastError = CONFIG_NO_ERROR;
  46.         return boost::lexical_cast<T>(match[1]);
  47.     }
  48.  
  49.     template<typename T>
  50.     void writeValue(const std::string& key, T value)
  51.     {
  52.         char prefix = typeid(T).name()[0];
  53.         std::string line = m_file->searchString(key);
  54.  
  55.         if (line.empty())
  56.             m_file->addContent(prefix + key + "=\"" + std::to_string(value) + "\"");
  57.         else
  58.             m_file->replaceString(line, prefix + key + "=\"" + std::to_string(value) + "\"");
  59.  
  60.         m_lastError = CONFIG_NO_ERROR;
  61.     }
  62.  
  63. private:
  64.     FileManager* m_file;
  65.  
  66. };
  67.  
  68. extern ConfigManager g_config;
  69.  
  70. #endif  // CONFIGMANAGER_H
  71.  
  72.  
  73.  
  74. #include "ConfigManager.h"
  75.  
  76. ConfigManager g_config;
  77.  
  78. void ConfigManager::init(const std::string & name)
  79. {
  80.     m_file = new FileManager(CONFIGS_DIRECTORY "/" + name);
  81.  
  82.     if (!m_file->isGood())
  83.         m_lastError = CONFIG_ERROR_OPEN;
  84. }
  85.  
  86. void ConfigManager::terminate()
  87. {
  88.     if (m_file->isGood())
  89.         m_file->save();
  90.  
  91.     delete m_file;
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement