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

Confaccess.h

#ifndef __CONFACCESS_H__ 
#define __CONFACCESS_H__ 

#include <pthread.h>
#include <stdlib.h>
#include <string>
#include <map>

class CConfAccess
{
    public:
        static CConfAccess* getInstance()
        {
            pthread_once(&once_, &initInstance);
            return pInstance_;
        }

        static void initInstance()
        {
            ::atexit(&destoryInstance);
            pInstance_ = new CConfAccess;
        }

        static void destoryInstance()
        {
            delete pInstance_;
        }

        bool Load(const std::string& filename);

        std::string GetValue(const std::string& strKey);

    private:
        CConfAccess() {};
        CConfAccess(const CConfAccess&);
        void operator=(const CConfAccess&);

        static CConfAccess* pInstance_;
        static pthread_once_t once_;

        std::map<std::string, std::string> mapKeyValue_; 
};


#endif //__CONFACCESS_H__ 



Confaccess.cpp

#include "Confaccess.h"
#include <fstream>

#define MAX_LINE 1024
using namespace std;

pthread_once_t CConfAccess::once_ = PTHREAD_ONCE_INIT;
CConfAccess* CConfAccess::pInstance_ = NULL;

//Trim space in the beginning and ending of the string.
string StrTrim(const string& strOriginal)
{
     static const char* whiteSpace = " \t\r\n";

     if (strOriginal.empty())
     {
        return strOriginal;
     }

     string::size_type uFrontPos = strOriginal.find_first_not_of(whiteSpace);

     if (string::npos == uFrontPos)
     {
        return "";
     }

     string::size_type uRearPos = strOriginal.find_last_not_of(whiteSpace);

     return string(strOriginal, uFrontPos, uRearPos - uFrontPos + 1);
}

bool CConfAccess::Load(const string& filename)
{
    ifstream initFile(filename.c_str());
    if (!initFile)
    {
        return false;
    }

    string strLine;
    while (getline(initFile, strLine))
    {   
        if ("" == StrTrim(strLine))
        {
            continue;
        }

        string::size_type uPos = strLine.find("#");
        if (uPos > 0 || (string::npos == uPos))
        {
            strLine = strLine.substr(0, uPos);
        }
        else
        {
            continue;
        }

        uPos = strLine.find("=");
        if (string::npos == uPos)
        {
            continue;
        }

        string strKey = StrTrim(strLine.substr(0, uPos));
        string strValue = StrTrim(strLine.substr(uPos + 1));
        
        mapKeyValue_[strKey] = strValue;
    }

    return true;
}

string CConfAccess::GetValue(const string& strKey)
{
    if (strKey.empty() || (mapKeyValue_.end() == mapKeyValue_.find(strKey)))
    {
        return "";
    }

    return mapKeyValue_[strKey];
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值