C++编写Config类读取配置文件2

参考:http://2309998.blog.51cto.com/2299998/1428166


#include<iostream>
#include <fstream>
#include <vector>
#include<string>
using namespace std;

class CConfigOperator
{
public:
	CConfigOperator(void);
	~CConfigOperator(void);
	void SetFilePath(const string &sFilePath);
	string GetFilePath();
	bool GetConfigValue(const string &sName, const string &skey, string &sValue, string &sError);
	bool ModefyConfigValue(const string &sName, const string &skey, const string &sValue, string &sError);

private:
	bool OpenFile();
	void FindName();
	bool FindKey();
	bool WriteFile();
	bool ModefyValue();
	void WriteToFile(vector<string> &vContent);

	fstream m_fout;
	ifstream m_fin;
	string m_sFilePath;
	string m_Name;
	string m_Key;
	string m_value;
	string m_sError;
	string m_sStr;
	bool m_bFindName;

};


//#include "ConfigOperator.h"
CConfigOperator::CConfigOperator(void)
{
}

CConfigOperator::~CConfigOperator(void)
{
}
/************************************

设置配置文件路径

************************************/
void CConfigOperator::SetFilePath(const string &sFilePath)
{
	m_sFilePath = sFilePath;
}



/************************************

得到配置文件路径

************************************/

string CConfigOperator::GetFilePath()
{
	return this->m_sFilePath;
}



/************************************

打开配置文件

************************************/
bool CConfigOperator::OpenFile()
{
	if (true == m_fin.is_open())
	{
		m_fin.close();
	}

	m_fin.open(m_sFilePath.c_str());
//	if (NULL == m_fin)
	if (m_fin.is_open() == false)
	{
		m_sError = "can not open file " + m_sFilePath;
		return false;
	}
	return true;
}

/************************************

查找配置文件的名字

************************************/
void CConfigOperator::FindName()
{
	if (-1 != m_sStr.find('['))
	{
		//name
		//string sTemp = m_sStr.substr(m_sStr.find('[') + 1, m_sStr.find(']') - m_sStr.find('[') - 1);
		string sTemp = m_sStr.substr(0, m_sStr.find('['));
		string::size_type idx = sTemp.find(m_Name);
		if (idx != string::npos)
		//if (0 == strcmp(sTemp.c_str(), m_Name.c_str()))
		{
			m_bFindName = true;
			m_sError = "Find Name But Not Find Key";
		}
		else
		{
			m_bFindName = false;
		}
	}
}

/************************************

查找配置文件的Key

************************************/
bool  CConfigOperator::FindKey()
{
	int iDelePlace = m_sStr.find('//');
	int iFindEqual = m_sStr.find('=');
	//被注释的行,或者是包含key但是已经被注视掉了,过滤

	if ((-1 != iDelePlace && iDelePlace <  iFindEqual) || (-1 != iDelePlace && -1 == iFindEqual) || -1 == iFindEqual)
	{
		return false;
	}

	//key 
	string sKey = m_sStr.substr(m_sStr.find('[') + 1, m_sStr.find(']') - m_sStr.find('[') - 1);
	//if (0 == strcmp(sKey.c_str(), m_Key.c_str()))

	string::size_type idx = sKey.find(m_Key);
	if (idx != string::npos)
	{
		m_value = m_sStr.substr(m_sStr.find('=') + 1, m_sStr.length() - m_sStr.find('=') - 1);
		return true;
	}
	return false;
}



/************************************

读取配置文件NEMA KEY 对应的Value信息

************************************/
bool CConfigOperator::GetConfigValue(const string &sName, const string &skey, string &sValue, string &sError)
{
	m_sError = "";
	m_Name = sName;
	m_Key = skey;

	if (false == OpenFile())
	{
		sError = m_sError;
		return false;
	}

	char str[1024];
	m_bFindName = false;

	//while (NULL != m_fin.getline(str, sizeof(str)))
	while (!m_fin.eof())
	{
		m_fin.getline(str, sizeof(str));
		m_sStr = str;
		FindName();
		if (true == m_bFindName)
		{
			if (true == FindKey())
			{
				m_fin.close();
				sError = "";
				sValue = m_value;
				return true;
			}
		}
	}

	sError = m_sError;
	m_fin.close();
	return false;

}

/************************************

写的方式打开文件

************************************/
bool CConfigOperator::WriteFile()
{
	m_fout.close();
	//关闭后要在清空一下,否则下次打开会出错

	m_fout.clear();
	m_fout.open(m_sFilePath.c_str(), ios::in | ios::out);
	//if (NULL == m_fout)
	if (m_fout.is_open() == false)
	{
		m_sError = "can not open file " + m_sFilePath;
		return false;
	}
	return true;
}



/************************************

修改配置文件Key对应的值
************************************/

bool  CConfigOperator::ModefyValue()
{
	int iDelePlace = m_sStr.find('//');
	int iFindEqual = m_sStr.find('=');
	//被注释的行,或者是包含key但是已经被注视掉了,过滤

	if ((-1 != iDelePlace && iDelePlace <  iFindEqual) || (-1 != iDelePlace && -1 == iFindEqual) || -1 == iFindEqual)
	{
		return false;
	}

	//key 
	string sKey = m_sStr.substr(m_sStr.find('[') + 1, m_sStr.find(']') - m_sStr.find('[') - 1);
	//if (0 == strcmp(sKey.c_str(), m_Key.c_str()))

	string::size_type idx = sKey.find(m_Key);
	if (idx != string::npos)
	{
		m_sStr = m_sStr.substr(0, m_sStr.find('=') + 1) + m_value;
		return true;
	}
	return false;

}

/************************************

修改后的配置文件信息重新写入文件

************************************/
void CConfigOperator::WriteToFile(vector<string> &vContent)
{
	if (false == WriteFile())
	{
		m_fout.close();
		return;
	}

	for (size_t iIndex = 0; iIndex < vContent.size(); iIndex++)
	{
		m_fout << vContent[iIndex] << endl;
	}

	m_fout.close();
	vector<string>().swap(vContent);
}

/************************************

修改配置文件NEMA KEY 对应的Value信息

************************************/

bool CConfigOperator::ModefyConfigValue(const string &sName, const string &skey, const string &sValue, string &sError)
{
	m_sError = "";
	m_Name = sName;
	m_Key = skey;
	m_value = sValue;
	if (false == WriteFile())
	{
		sError = m_sError;
		return false;
	}

	char str[1024];
	m_bFindName = false;
	vector<string> vContent;
	bool isModefy = false;

	//while (NULL != m_fout.getline(str, sizeof(str)))
	while (!m_fout.eof())
	{
		m_fout.getline(str, sizeof(str));
		m_sStr = str;

		FindName();
		if (true == m_bFindName)
		{
			if (true == ModefyValue())
			{
				isModefy = true;
			}
		}

		vContent.push_back(m_sStr);
	}

	sError = m_sError;
	WriteToFile(vContent);
	m_fout.close();
	return isModefy;

}


int main()
{
	//name1[key1] = faddga   解析格式
	CConfigOperator tCConfigOperator;

	string sFielPath = "cfg.txt";

	tCConfigOperator.SetFilePath(sFielPath);

	string sName = "name1";
	string sKey  = "key1";
	string sValue = "";
	string sEroor = "";

	tCConfigOperator.GetConfigValue(sName, sKey, sValue, sEroor);

	cout << "valuse is  " << sValue << "  sEroor is" << sEroor << endl;

	sValue = "ssss1123312";

	tCConfigOperator.ModefyConfigValue(sName, sKey, sValue, sEroor);
	tCConfigOperator.GetConfigValue(sName, sKey, sValue, sEroor);

	cout << "valuse is " << sValue << "   sEroor is" << sEroor << endl;

	getchar();

	return 0;

}

保存自定义格式到配置文件,一般可以使用以下步骤: 1. 定义数据结构 首先,你需要定义一个数据结构来保存你的配置信息。例如: ```c typedef struct { int width; int height; char font[16]; int fontsize; } Config; ``` 这个结构体包含了一个窗口的宽度、高度、字体名称和字体大小等信息。 2. 读取配置文件 接下来,你需要编写一个函数来读取配置文件并将其解析为你的配置信息。例如: ```c int read_config(const char* filename, Config* config) { FILE* fp = fopen(filename, "r"); if (fp == NULL) { return -1; } char line[256]; while (fgets(line, sizeof(line), fp)) { // 解析配置信息 // ... } fclose(fp); return 0; } ``` 在这个函数中,你需要打开配置文件,逐行读取文件内容并解析配置信息。你可以使用 C 标准库中的 `fgets()` 函数来读取文件内容,然后使用字符串处理函数来解析每行的数据。 3. 保存配置文件 最后,你需要编写一个函数来将配置信息保存到文件中。例如: ```c int save_config(const char* filename, const Config* config) { FILE* fp = fopen(filename, "w"); if (fp == NULL) { return -1; } fprintf(fp, "width=%d\n", config->width); fprintf(fp, "height=%d\n", config->height); fprintf(fp, "font=%s\n", config->font); fprintf(fp, "fontsize=%d\n", config->fontsize); fclose(fp); return 0; } ``` 在这个函数中,你需要打开文件并使用 C 标准库中的 `fprintf()` 函数将配置信息写入文件。注意,你需要按照自己定义的格式来写入数据。 最后,你可以在主程序中使用这些函数来读取和保存配置信息: ```c int main() { Config config; read_config("config.ini", &config); // 修改配置信息 // ... save_config("config.ini", &config); return 0; } ``` 这样,你就可以使用自定义格式保存配置信息了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小新识图

你的鼓励是我最大的分享动力。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值