.h
#include <afxcoll.h>
class CIniMgr
{
public:
// 设定INI文件的名字,要完全路径名
void setINIFileName(CString strINIFile);
// 获取段类所有数据
CStringList* getSectionData(CString strSection);
// 所有段名
CStringList* getSectionNames();
// 判断段名是否已经存在
BOOL sectionExists(CString strSection);
// 设置键值
long setKey(CString strValue, CString strKey, CString strSection);
// 获得键值
CString getKeyValue(CString strKey,CString strSection);
// 构造函数
CIniMgr()
{
m_sectionList = new CStringList();
m_sectionDataList = new CStringList();
}
// 带文件名参数的构造函数
CIniMgr(CString strFile)
{
m_strFileName = strFile;
m_sectionList = new CStringList();
m_sectionDataList = new CStringList();
}
// 析构清空链表释放
~CIniMgr()
{
delete m_sectionList;
delete m_sectionDataList;
}
private:
CStringList *m_sectionDataList;
CStringList *m_sectionList;
CString m_strSection;
long m_lRetValue;
CString m_strFileName;
};
.c
#include "stdafx.h"
#include "IniMgr.h"
#include <afxcoll.h>
CString CIniMgr::getKeyValue(CString strKey,CString strSection)
{
char ac_Result[255];
m_lRetValue = GetPrivateProfileString((LPCTSTR)strSection,(LPCTSTR)strKey,
"",ac_Result, 255, (LPCTSTR)m_strFileName);
CString strResult(ac_Result);
return strResult;
}
long CIniMgr::setKey(CString strValue, CString strKey, CString strSection)
{
m_lRetValue = WritePrivateProfileString (strSection, strKey,
strValue, m_strFileName);
return m_lRetValue;
}
BOOL CIniMgr::sectionExists(CString strSection)
{
char ac_Result[100];
CString csAux;
m_lRetValue = GetPrivateProfileString((LPCTSTR)strSection,NULL,
"",ac_Result, 90, (LPCTSTR)m_strFileName);
return (m_lRetValue > 0);
}
CStringList* CIniMgr::getSectionNames()
{
char ac_Result[2000];
m_sectionList->RemoveAll();
m_lRetValue = GetPrivateProfileSectionNames(ac_Result,2000,(LPCTSTR)m_strFileName);
CString strSectionName;
for(int i=0; i<m_lRetValue; i++)
{
if(ac_Result[i] != '\0') {
strSectionName = strSectionName + ac_Result[i];
} else {
if(strSectionName != "") {
m_sectionList->InsertAfter(m_sectionList->GetTailPosition(),strSectionName);
}
strSectionName = "";
}
}
return m_sectionList;
}
CStringList* CIniMgr::getSectionData(CString strSection)
{
char ac_Result[2000];
m_sectionDataList->RemoveAll();
m_lRetValue = GetPrivateProfileSection((LPCTSTR)strSection, ac_Result, 2000, (LPCTSTR)m_strFileName);
CString strSectionData;
for(int i=0; i<m_lRetValue; i++)
{
if(ac_Result[i] != '=') { // 以前为if(ac_Result[i] != '\0') {
strSectionData = strSectionData + ac_Result[i];
} else {
if(strSectionData != "") {
m_sectionDataList->InsertAfter(m_sectionDataList->GetTailPosition(),strSectionData);
}
strSectionData = "";
}
}
return m_sectionDataList;
}
void CIniMgr::setINIFileName(CString strINIFile)
{
m_strFileName = strINIFile;
}