网络服务器软件开发/中间件开发,关注ACE/ICE/boost

C++博客 首页 新随笔 联系 聚合 管理
  152 Posts :: 3 Stories :: 172 Comments :: 0 Trackbacks
     自从做公司的SNS社区以来,写了不少的C#代码,与C++相比,C#是易于使用的,开发效率提高很多倍,其中印象比较深刻的是,在一个C#工程中,可以通过向导添加配置文件,默认文件名为App.Config,是XML格式,一般内容为:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
     
    
<appSettings>

        
<add key="Ip" value="localhost"/>
        
<add key="Port" value="8888"/>
        
<add key="ServiceName" value="Indexer"/>


    
</appSettings>
    
</configuration>
通过在appSettings里面添加add元素,即可实现通常的配置功能,更重要的是,可以进一步扩展为多级的树形结构,与Ini格式相比,更直观,可读性更强,下面是基于CMarkup(http://www.firstobject.com/)的一个简单实现:
头文件如下:
#pragma once

#include 
<string>
#include 
<map>


class AppConfig
{
public:
    AppConfig(
void);
    
~AppConfig(void);

    
int        GetInt(std::string key);
    std::
string    GetString(std::string key);
private:
    std::map
<std::string,std::string> config_map_;
}
;
 
extern AppConfig appConfig;
源文件如下:

#include 
"AppConfig.h"
#include 
"Markup.h"

AppConfig appConfig;


AppConfig::AppConfig(
void)
{
    CMarkup parser;
    
if (!parser.Load( "App.Config"  ))
    
{
        
return;        
    }

    
if (parser.FindChildElem("appSettings"))
    
{
        parser.IntoElem();
        
while (parser.FindChildElem("add"))
        
{
            std::
string key = parser.GetChildAttrib("key");
            std::
string value = parser.GetChildAttrib("value");
            config_map_[key] 
= value;
        }

        parser.OutOfElem();
    }

    
}


AppConfig::
~AppConfig(void)
{
}


int AppConfig::GetInt( std::string key )
{
    
if (config_map_.find(key) != config_map_.end())
    
{
        
return atoi(config_map_[key].c_str());
    }

    
else
    
{
        
return 0;
    }

}


std::
string AppConfig::GetString( std::string key )
{
    
if (config_map_.find(key) != config_map_.end())
    
{
        
return config_map_[key];
    }

    
else
    
{
        
return "";
    }

}

测试代码为:
// MarkupTest.cpp : 定义控制台应用程序的入口点。
//

#include 
"stdafx.h"

#include 
"AppConfig.h"
#include 
<iostream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{    
    cout 
<< appConfig.GetString("Ip")  << "-----" << appConfig.GetInt("Port")  << "----" << appConfig.GetString("ServiceName"<< endl;
    
return 0;
}


posted on 2010-12-29 00:25 true 阅读(2500) 评论(0)  编辑 收藏 引用 所属分类: 其它开源库C++基础

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理