一份采用单例模式编写,可读取配置文件的代码

以你之姓@ 2022-08-07 13:54 135阅读 0赞

Confaccess.h

  1. #ifndef __CONFACCESS_H__
  2. #define __CONFACCESS_H__
  3. #include <pthread.h>
  4. #include <stdlib.h>
  5. #include <string>
  6. #include <map>
  7. class CConfAccess
  8. {
  9. public:
  10. static CConfAccess* getInstance()
  11. {
  12. pthread_once(&once_, &initInstance);
  13. return pInstance_;
  14. }
  15. static void initInstance()
  16. {
  17. ::atexit(&destoryInstance);
  18. pInstance_ = new CConfAccess;
  19. }
  20. static void destoryInstance()
  21. {
  22. delete pInstance_;
  23. }
  24. bool Load(const std::string& filename);
  25. std::string GetValue(const std::string& strKey);
  26. private:
  27. CConfAccess() {};
  28. CConfAccess(const CConfAccess&);
  29. void operator=(const CConfAccess&);
  30. static CConfAccess* pInstance_;
  31. static pthread_once_t once_;
  32. std::map<std::string, std::string> mapKeyValue_;
  33. };
  34. #endif //__CONFACCESS_H__

Confaccess.cpp

  1. #include "Confaccess.h"
  2. #include <fstream>
  3. #define MAX_LINE 1024
  4. using namespace std;
  5. pthread_once_t CConfAccess::once_ = PTHREAD_ONCE_INIT;
  6. CConfAccess* CConfAccess::pInstance_ = NULL;
  7. //Trim space in the beginning and ending of the string.
  8. string StrTrim(const string& strOriginal)
  9. {
  10. static const char* whiteSpace = " \t\r\n";
  11. if (strOriginal.empty())
  12. {
  13. return strOriginal;
  14. }
  15. string::size_type uFrontPos = strOriginal.find_first_not_of(whiteSpace);
  16. if (string::npos == uFrontPos)
  17. {
  18. return "";
  19. }
  20. string::size_type uRearPos = strOriginal.find_last_not_of(whiteSpace);
  21. return string(strOriginal, uFrontPos, uRearPos - uFrontPos + 1);
  22. }
  23. bool CConfAccess::Load(const string& filename)
  24. {
  25. ifstream initFile(filename.c_str());
  26. if (!initFile)
  27. {
  28. return false;
  29. }
  30. string strLine;
  31. while (getline(initFile, strLine))
  32. {
  33. if ("" == StrTrim(strLine))
  34. {
  35. continue;
  36. }
  37. string::size_type uPos = strLine.find("#");
  38. if (uPos > 0 || (string::npos == uPos))
  39. {
  40. strLine = strLine.substr(0, uPos);
  41. }
  42. else
  43. {
  44. continue;
  45. }
  46. uPos = strLine.find("=");
  47. if (string::npos == uPos)
  48. {
  49. continue;
  50. }
  51. string strKey = StrTrim(strLine.substr(0, uPos));
  52. string strValue = StrTrim(strLine.substr(uPos + 1));
  53. mapKeyValue_[strKey] = strValue;
  54. }
  55. return true;
  56. }
  57. string CConfAccess::GetValue(const string& strKey)
  58. {
  59. if (strKey.empty() || (mapKeyValue_.end() == mapKeyValue_.find(strKey)))
  60. {
  61. return "";
  62. }
  63. return mapKeyValue_[strKey];
  64. }

发表评论

表情:
评论列表 (有 0 条评论,135人围观)

还没有评论,来说两句吧...

相关阅读

    相关 设计模式)-模式

    单例模式是设计模式中比较简单的一种模式,也是使用的比较多的一种模式。         特别是在某些对象只需要一个时,比如线程池、缓存、日志对象、注册表对象等。