工具类库系列(三)-IniReader

Ini配置文件读取工具
本文介绍了一个简单的Ini配置文件读取工具类IniReader,该工具封装了boost库的ptree来实现Ini文件的解析与读取。文章提供了完整的源代码实现,并展示了如何初始化Ini文件及从中获取字符串和无符号整数类型的值。

第三个工具类:IniReader


就是读ini配置文件的一个工具类,很简单,就是封装了一下boost库的ptree


IniReader.h

#ifndef __IniReader_h__
#define __IniReader_h__

#include <string>
#include <boost/property_tree/ptree.hpp>

namespace common{
	namespace tool{

		class IniReader
		{
		public:
			IniReader();
			~IniReader();

			bool InitIni(const std::string& path);

			bool GetValue(const std::string& root, const std::string& key, std::string& value);

			bool GetValue(const std::string& root, const std::string& key, unsigned int& value);

		private:
			bool m_IsInit;
			boost::property_tree::ptree m_Pt;
		};

	}
}

#endif

IniReader.cpp

#include "IniReader.h"

#include <boost/property_tree/ini_parser.hpp>

namespace common{
	namespace tool{

		IniReader::IniReader()
		{
			m_IsInit = false;
		}

		IniReader::~IniReader()
		{

		}

		bool IniReader::InitIni(const std::string& path)
		{
			try
			{
				boost::property_tree::ini_parser::read_ini(path, m_Pt);
				m_IsInit = true;
			}
			catch (...)
			{
				m_IsInit = false;
			}

			return m_IsInit;
		}

		bool IniReader::GetValue(const std::string& root, const std::string& key, std::string& value)
		{
			if (m_IsInit)
			{
				try
				{
					std::string strTemp(root + "." + key);
					value = m_Pt.get<std::string>(strTemp);
					return true;
				}
				catch (...)
				{
					return false;
				}
			}
			else
			{
				return false;
			}
		}

		bool IniReader::GetValue(const std::string& root, const std::string& key, unsigned int& value)
		{
			if (m_IsInit)
			{
				try
				{
					std::string strTemp(root + "." + key);
					value = m_Pt.get<unsigned int>(strTemp);
					return true;
				}
				catch (...)
				{
					return false;
				}
			}
			else
			{
				return false;
			}
		}

	}
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值