MFC总结(7)--- 操作Ini文件 操作

本文介绍了如何在MFC中创建一个专门用于操作Ini文件的类,将读写Ini文件的方法封装起来,方便在项目中复用。详细讲述了类的定义和使用方法。

  1、建立一个操作Ini文件的类,将操作ini文件的相关方法都封装到该类中


MyIniClass.h文件

#pragma once
#include <vector>

using std::vector;


class CMyIniClass
{
public:
	CMyIniClass();
	virtual ~CMyIniClass();

	//    设置ini文件路径
	//    成功返回TRUE;否则返回FALSE
	BOOL         SetPath(CString strPath);

	//    检查section是否存在
	//    存在返回TRUE;否则返回FALSE
	BOOL         SectionExist(CString strSection);

	//    从指定的Section和Key读取KeyValue
	//    返回KeyValue
	CString         GetKeyValue(CString    strSection,
		CString    strKey);

	//    设置Section、Key以及KeyValue,若Section或者Key不存在则创建
	void          SetKeyValue(CString    strSection,
		CString    strKey,
		CString    strKeyValue);

	//    删除指定Section下的一个Key
	void          DeleteKey(CString strSection,
		CString strKey);

	//    删除指定的Section以及其下的所有Key
	void          DeleteSection(CString strSection);

	//    获得所有的Section
	//    返回Section数目
	int              GetAllSections(CStringArray& strArrSection);

	//    根据指定Section得到其下的所有Key和KeyValue
	//    返回Key的数目
	int              GetAllKeysAndValues(CString strSection,
		CStringArray& strArrKey,
		CStringArray& strArrKeyValue);

	//       删除所有Section
	void          DeleteAllSections();

	//初始化信息
	void initIniFile(LPCTSTR path);

	//	获取指定ini中节中所有的value
	void getValue(CString strPath, CString strSections);

	//返回vector
	vector<CString>  getValueVctr();

	void getSysCurName(CString & strName);
private:
	//       ini文件路径
	CString m_strPath;
	vector<CString> m_valueVctr;
};


MyIniClass.cpp文件

#include "stdafx.h"
#include "MyIniClass.h"



#define         MAX_SECTION                260        //Section最大长度
#define         MAX_KEY                         260        //KeyValues最大长度
#define         MAX_ALLSECTIONS     65535    //所有Section的最大长度
#define         MAX_ALLKEYS              65535    //所有KeyValue的最大长度
CMyIniClass::CMyIniClass() : m_valueVctr(NULL)
{
}


CMyIniClass::~CMyIniClass()
{
}
//////////////////////////////////////////////////////////////////////////
//   Public Functions
//////////////////////////////////////////////////////////////////////////

BOOL CMyIniClass::SetPath(CString strPath)
{
	m_strPath = strPath;

	//       检查文件是否存在
	DWORD  dwFlag = GetFileAttributes((LPCTSTR)m_strPath);

	//       文件或者路径不存在,返回FALSE
	if (0xFFFFFFFF == dwFlag)
		return FALSE;

	//       路径是目录,返回FALSE
	if (FILE_ATTRIBUTE_DIRECTORY & dwFlag)
		return FALSE;

	return TRUE;
}

BOOL CMyIniClass::SectionExist(CString strSection)
{
	TCHAR chSection[MAX_SECTION];
	DWORD dwRetValue;

	dwRetValue = GetPrivateProfileString(
		(LPCTSTR)strSection,
		NULL,
		_T(""),
		chSection,
		sizeof(chSection) / sizeof(TCHAR),
		(LPCTSTR)m_strPath);

	return (dwRetValue > 0);
}

CString CMyIniClass::GetKeyValue(CString strSection,
	CString strKey)
{
	TCHAR         chKey[MAX_KEY];
	DWORD         dwRetValue;
	CString strKeyValue = _T("");

	dwRetValue = GetPrivateProfileString(
		(LPCTSTR)strSection,
		(LPCTSTR)strKey,
		_T(""),
		chKey,
		sizeof(chKey) / sizeof(TCHAR),
		(LPCTSTR)m_strPath);

	strKeyValue = chKey;

	return strKeyValue;

}

void CMyIniClass::SetKeyValue(CString strSection,
	CString strKey,
	CString strKeyValue)
{
	WritePrivateProfileString(
		(LPCTSTR)strSection,
		(LPCTSTR)strKey,
		(LPCTSTR)strKeyValue,
		(LPCTSTR)m_strPath);
}

void CMyIniClass::DeleteKey(CString strSection, CString strKey)
{
	WritePrivateProfileString(
		(LPCTSTR)strSection,
		(LPCTSTR)strKey,
		NULL,          //       这里写NULL,则删除Key
		(LPCTSTR)m_strPath);
}

void CMyIniClass::DeleteSection(CString strSection)
{
	WritePrivateProfileString(
		(LPCTSTR)strSection,
		NULL,
		NULL,          //       这里都写NULL,则删除Section
		(LPCTSTR)m_strPath);
}

int CMyIniClass::GetAllSections(CStringArray& strArrSection)
{
	int dwRetValue, i, j, iPos = 0;
	TCHAR chAllSections[MAX_ALLSECTIONS];
	TCHAR chTempSection[MAX_SECTION];

	ZeroMemory(chAllSections, MAX_ALLSECTIONS);
	ZeroMemory(chTempSection, MAX_SECTION);

	dwRetValue = GetPrivateProfileSectionNames(
		chAllSections,
		MAX_ALLSECTIONS,
		m_strPath);

	//       因为Section在数组中的存放形式为“Section1”,0,“Section2”,0,0。
	//       所以如果检测到连续两个0,则break
	for (i = 0; i < MAX_ALLSECTIONS; i++)
	{
		if (chAllSections[i] == NULL)
		{
			if (chAllSections[i] == chAllSections[i + 1])
				break;
		}
	}

	i++; //         保证数据读完
	strArrSection.RemoveAll(); //         清空数组

	for (j = 0; j < i; j++)
	{
		chTempSection[iPos++] = chAllSections[j];
		if (chAllSections[j] == NULL)
		{
			strArrSection.Add(chTempSection);
			ZeroMemory(chTempSection, MAX_SECTION);
			iPos = 0;
		}
	}

	return strArrSection.GetSize();
}

int CMyIniClass::GetAllKeysAndValues(CString  strSection,
	CStringArray&         strArrKey,
	CStringArray& strArrKeyValue)
{
	int dwRetValue, i, j, iPos = 0;
	TCHAR chAllKeysAndValues[MAX_ALLKEYS];
	TCHAR chTempkeyAndValue[MAX_KEY];
	CString strTempKey;

	ZeroMemory(chAllKeysAndValues, MAX_ALLKEYS);
	ZeroMemory(chTempkeyAndValue, MAX_KEY);

	dwRetValue = GetPrivateProfileSection(
		strSection,
		chAllKeysAndValues,
		MAX_ALLKEYS,
		m_strPath);

	//       因为Section在数组中的存放形式为“Key1=KeyValue1”,0,“Key2=KeyValue2”,0
	//       所以如果检测到连续两个0,则break
	for (i = 0; i < MAX_ALLSECTIONS; i++)
	{
		if (chAllKeysAndValues[i] == NULL)
		{
			if (chAllKeysAndValues[i] == chAllKeysAndValues[i + 1])
				break;
		}
	}

	i++;
	strArrKey.RemoveAll();
	strArrKeyValue.RemoveAll();

	for (j = 0; j < i; j++)
	{
		chTempkeyAndValue[iPos++] = chAllKeysAndValues[j];
		if (chAllKeysAndValues[j] == NULL)
		{
			strTempKey = chTempkeyAndValue;
			strArrKey.Add(strTempKey.Left(strTempKey.Find('=')));
			strArrKeyValue.Add(strTempKey.Mid(strTempKey.Find('=') + 1));
			ZeroMemory(chTempkeyAndValue, MAX_KEY);
			iPos = 0;
		}
	}

	return strArrKey.GetSize();
}

void CMyIniClass::DeleteAllSections()
{
	int nSecNum;
	CStringArray strArrSection;
	nSecNum = GetAllSections(strArrSection);
	for (int i = 0; i < nSecNum; i++)
	{
		WritePrivateProfileString(
			(LPCTSTR)strArrSection[i],
			NULL,
			NULL,
			(LPCTSTR)m_strPath);
	}
}


/************************************************************************/
/* 函数名称:getValue
/* 函数功能:讲获取到的数据封装到成员变量vector中
/* 参数1:	ini文件路径
/* 参数2:	section名称
/* 返回值:
/* 说明:
/************************************************************************/
void CMyIniClass::getValue(CString strPath, CString strSections)
{

	CMyIniClass file;
	CStringArray arrSection, arrKey, arrkeyValue;
	//file.SetPath(L".\\myfile.ini");
	file.SetPath(strPath);
	CString str = L"";

	if (file.SectionExist(strSections))
	{

		// 		//得到所有section
		// 		int num = file.GetAllSections(arrSection);
		// 		str = "";
		// 		for (int i = 0; i < num; i++)
		// 		{
		// 			str += arrSection[i] + L" ";//str="student computer ";
		// 		}

		//得到所有Key和KeyValue
		int num = file.GetAllKeysAndValues(strSections, arrKey, arrkeyValue);
		str = L"";
		for (int j = 0; j < num; j++)
		{
			//arrKey保存了computer下所有的Key
			//arrkeyValue保存了computer下所有的KeyValue
			//str = arrKey[j];
			str = arrkeyValue[j];
			m_valueVctr.push_back(str);
		}
	}
}

vector<CString> CMyIniClass::getValueVctr()
{

	return m_valueVctr;
}


void CMyIniClass::initIniFile(LPCTSTR path)
{
	//::WritePrivateProfileStringW(_T("WINDOWS_DELETE"), _T("wintemp"), _T("c:\\windows\\temp"), _T(".\\myIni.ini"));

	//获取当前的系统登陆的用户名
	CString   strName;
	getSysCurName(strName);

	//拼接用户临时文件
	CString strUserTemp;
	strUserTemp.Format(_T("C:\\Users\\%s\\AppData\\Local\\Temp"), strName);

	//拼接浏览器历史记录
	CString strBroTemp;
	strBroTemp.Format(_T("C:\\Users\\%s\\AppData\\Local\\Microsoft\\Windows\\Temporary Internet Files"), strName);

	::WritePrivateProfileStringW(_T("WINDOWS_DELETE"), _T("wintemp"), _T("C:\\windows\\temp"), path);
	::WritePrivateProfileStringW(_T("WINDOWS_DELETE"), _T("usertemp"), strUserTemp, path);


	::WritePrivateProfileStringW(_T("BROWSER_DELETE"), _T("browsertemp"), strBroTemp, path);

}


/************************************************************************/
/* 函数名称:getSysCurName
/* 函数功能: 获取当前登陆用户名
/* 参数1:
/* 参数2:
/* 返回值:
/* 说明:
/************************************************************************/
void CMyIniClass::getSysCurName(CString & strName)
{
	WCHAR UserName[MAX_PATH];
	//	CString StrUserName;
	DWORD Size = MAX_PATH;
	::GetUserName(UserName, &Size);
	strName.Format(L"%s ", UserName);
}


2、在mfc中的按钮事件中进行调用

	//判断ini配置文件是否存在   不存在则创建
	CString path = _T(".\\myIni.ini");

	if (!m_IniFile.SectionExist(path))
	{
		m_IniFile.initIniFile(path);
	}

也可以使用如下进行测试

  void CMFCApplication1Dlg::OnBnClickedButton1()
{      CIniFile file;
         CStringArray arrSection, arrKey, arrkeyValue;
         file.SetPath("f:\\ myfile.ini");
         CString str="";
 
         if(file.SectionExist("student"))
         {
                  //str="15"
                   str = file.GetKeyValue("student", "female");
                  
                   //设置number为50
                  file.SetKeyValue("student", "number", "50");
 
                   //因为在student中computer_num不存在,所以增加一项
                  file.SetKeyValue("student", "computer_num", "30");
 
                   //得到所有section
                   int num = file.GetAllSections(arrSection);
                   str = "";
                   for(int i=0; i<num; i++)
                   {
                            str += arrSection[i] + " ";//str="student computer ";
                   }
 
                   //得到所有Key和KeyValue
                   int num = file.GetAllKeysAndValues("computer", arrKey, arrkeyValue);
                   str = "";
                   for(int j=0; j<num; j++)
                   {
                            //arrKey保存了computer下所有的Key
                            //arrkeyValue保存了computer下所有的KeyValue
                            str = arrKey[j];
                            str = arrkeyValue[j];
                   }
                   //删除student下的computer_num
                  file.DeleteKey("student", "computer_num");
 
                   //删除student
                  file.DeleteSection("student");
     } }



 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值