前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【C++】基础:读取ini配置信息

【C++】基础:读取ini配置信息

作者头像
DevFrank
发布2024-07-24 15:30:34
1150
发布2024-07-24 15:30:34
举报
文章被收录于专栏:C++开发学习交流

😏1. ini配置

INI(初始化)文件是一种文本文件,它用于存储配置数据。INI 文件通常由一些节组成,每个节有其自己的键-值对。INI 文件最初是由微软开发的,用于在 Windows 操作系统中存储应用程序的配置信息。

INI 文件格式非常简单,它包含了以下三种元素:

节(section):一个节用方括号 [] 包围,节名在方括号内,如 [Section1]。 键(key):键表示配置项的名称,键和值之间使用等号 = 分隔,如 Key1=Value1。 值(value):值表示键所对应的配置项的值。

😊2. 头文件

下面演示一个头文件用于读取ini,可在项目中引用。

代码语言:javascript
复制
#ifndef INI_H_
#define INI_H_

#include <string>
#include <map>
#include <fstream>
 
namespace ini
{
	class iniReader
	{
	private:
		std::map<std::string, std::map<std::string, std::string> >settings_;
		
	public:
		iniReader(){}
		~iniReader(){}

		bool ReadConfig(const std::string &filename)
		{
			settings_.clear();
			std::ifstream infile(filename.c_str());//构造默认调用open,所以可以不调用open
			//std::ifstream infile;
			//infile.open(filename.c_str());
			//bool ret = infile.is_open()
			if (!infile) {
				return false;
			}
			std::string line, key, value, section;
			std::map<std::string, std::string> k_v;
			std::map<std::string, std::map<std::string, std::string> >::iterator it;
			while (getline(infile, line))
			{
				if (AnalyseLine(line, section, key, value))
				{
					it = settings_.find(section);
					if (it != settings_.end())
					{
						k_v[key] = value;
						it->second = k_v;
					}
					else
					{
						k_v.clear();
						settings_.insert(std::make_pair(section, k_v));
					}
				}
				key.clear();
				value.clear();
			}
			infile.close();
			return true;
		}
 
		std::string ReadString(const char* section, const char* item, const char* default_value)
		{
			std::string tmp_s(section);
			std::string tmp_i(item);
			std::string def(default_value);
			std::map<std::string, std::string> k_v;
			std::map<std::string, std::string>::iterator it_item;
			std::map<std::string, std::map<std::string, std::string> >::iterator it;
			it = settings_.find(tmp_s);
			if (it == settings_.end())
			{
				return def;
			}
			k_v = it->second;
			it_item = k_v.find(tmp_i);
			if (it_item == k_v.end())
			{
				return def;
			}
			return it_item->second;
		}
 
		int ReadInt(const char* section, const char* item, const int& default_value)
		{
			std::string tmp_s(section);
			std::string tmp_i(item);
			std::map<std::string, std::string> k_v;
			std::map<std::string, std::string>::iterator it_item;
			std::map<std::string, std::map<std::string, std::string> >::iterator it;
			it = settings_.find(tmp_s);
			if (it == settings_.end())
			{
				return default_value;
			}
			k_v = it->second;
			it_item = k_v.find(tmp_i);
			if (it_item == k_v.end())
			{
				return default_value;
			}
			return atoi(it_item->second.c_str());
		}
 
		float ReadFloat(const char* section, const char* item, const float& default_value)
		{
			std::string tmp_s(section);
			std::string tmp_i(item);
			std::map<std::string, std::string> k_v;
			std::map<std::string, std::string>::iterator it_item;
			std::map<std::string, std::map<std::string, std::string> >::iterator it;
			it = settings_.find(tmp_s);
			if (it == settings_.end())
			{
				return default_value;
			}
			k_v = it->second;
			it_item = k_v.find(tmp_i);
			if (it_item == k_v.end())
			{
				return default_value;
			}
			return atof(it_item->second.c_str());
		}
 
	private:
		bool IsSpace(char c)
		{
			if (' ' == c || '\t' == c)
				return true;
			return false;
		}
		
		bool IsCommentChar(char c)
		{
			switch (c) 
			{
			case '#':
				return true;
			default:
				return false;
			}
		}
 
		void Trim(std::string & str)
		{
			if (str.empty())
			{
				return;
			}
			int i, start_pos, end_pos;
			for (i = 0; i < str.size(); ++i) {
				if (!IsSpace(str[i])) {
					break;
				}
			}
			if (i == str.size())
			{
				str = "";
				return;
			}
			start_pos = i;
			for (i = str.size() - 1; i >= 0; --i) {
				if (!IsSpace(str[i])) {
					break;
				}
			}
			end_pos = i;
			str = str.substr(start_pos, end_pos - start_pos + 1);
		}
 
		bool AnalyseLine(const std::string & line, std::string& section, std::string & key, std::string & value)
		{
			if (line.empty())
				return false;
			int start_pos = 0, end_pos = line.size() - 1, pos, s_startpos, s_endpos;
			if ((pos = line.find("#")) != -1)
			{
				if (0 == pos)
				{
					return false;
				}
				end_pos = pos - 1;
			}
			if (((s_startpos = line.find("[")) != -1) && ((s_endpos = line.find("]"))) != -1)
			{
				section = line.substr(s_startpos + 1, s_endpos - 1);
				return true;
			}
			std::string new_line = line.substr(start_pos, start_pos + 1 - end_pos);
			if ((pos = new_line.find('=')) == -1)
				return false;
			key = new_line.substr(0, pos);
			value = new_line.substr(pos + 1, end_pos + 1 - (pos + 1));
			Trim(key);
			if (key.empty()) {
				return false;
			}
			Trim(value);
			if ((pos = value.find("\r")) > 0)
			{
				value.replace(pos, 1, "");
			}
			if ((pos = value.find("\n")) > 0)
			{
				value.replace(pos, 1, "");
			}
			return true;
		}

	};
}	// namespace ini

#endif

😆3. 测试程序

先创建一个ini:

代码语言:javascript
复制
[g1]
name = group1
IP = 192.168.1.100
port = 8000
[g2]
name =  group2
IP = 192.168.1.101
port = 8001

然后创建main.cpp用于测试:

代码语言:javascript
复制
#include <iostream>
#include "config_ini.h"
 
int main() 
{
	ini::iniReader config;
	bool ret = config.ReadConfig("config.ini");
	if (ret == false) 
    {
		printf("ReadConfig is Error, filename=%s", "config.ini");
		return 1;
	}

	std::string HostName = config.ReadString("g1", "name", "");
	std::string IP = config.ReadString("g1", "IP", "");
	int Port = config.ReadInt("g1", "port", 0);
 
	std::cout << "HostName=" << HostName << std::endl;
	std::cout << "IP=" << IP << std::endl;
	std::cout << "Port=" << Port << std::endl;
 
	return 0;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2024-01-17,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 😏1. ini配置
  • 😊2. 头文件
  • 😆3. 测试程序
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档