前注: 这是自己平时写的一些小代码,未必有用及符合设计原则,若有不妥之处,还请大家指教。
说明:
虽然INI这种配置文件早已不被微软所推荐,但至少在VC6下用C++编写一些小程序时,用INI还是有其长处的:简单的INI要比简单的XML更加直观(当然在复杂情况则相反);Windows提供了专门的API来读写INI配置,只需一条语句即可。
不过在最近写的几个小程序中,也发现了私有配置文件读写API的一些问题:
1. 要获取配置文件的全局路径,并在每次调用API传递;
2. Windows没有提供写整形数据的API;
3. 经常把GetPrivateProfileXXX写成GetPrifileXXX。
所以,自己封装了一个类,其实就是一个非常简单的封装,函数名简短了些,函数参数少了些。额,我常常干这事,为了代码的一些微不足道(很多别人应该是这么以为的)的美观或调用上的简化做一些极简单的封装。
要点如下:
1. 提供了两个成员变量来保存配置文件路径和段名,使向外公布的读写接口不必带有这两个参数。至少对我的大多数小程序来说,这两个数据都是唯一的。
2. 提供了一个默认配置文件路径:在当前模块所在目录下,与当前模块同名,以INI为后缀名。
3. 提供了一个写INT形数据的接口,使用的方法是网上找的。先转换为字符串,再写。
4. 提供的GetString直接返回CString对象,不用调用方去分配内存了。
头文件:
class CProfile
{
public:
static DWORD GetDefaultProfile(LPTSTR lpBuffer, UINT uSize);
CProfile();
CProfile(LPCTSTR strFile);
virtual ~CProfile();
public:
BOOL GetStruct(LPCTSTR key, LPVOID lpStruct, UINT uSize, LPCTSTR section = NULL);
DWORD GetSectionNames(LPTSTR lpReturnedString, DWORD nSize);
DWORD GetSection(LPTSTR lpReturnedString, DWORD nSize, LPCTSTR section = NULL);
CString GetString(LPCTSTR key, LPCTSTR strDefault = NULL, LPCTSTR section = NULL);
INT GetInt(LPCTSTR key, INT nDefault = 0, LPCTSTR section = NULL);
BOOL WriteStruct(LPCTSTR key, LPVOID lpStruct, UINT uSize, LPCTSTR section = NULL);
BOOL WriteInt(LPCTSTR key, INT iValue, LPCTSTR section = NULL);
BOOL WriteString(LPCTSTR key, LPCTSTR lpString, LPCTSTR section = NULL);
BOOL WriteSection(LPCTSTR lpString, LPCTSTR section = NULL);
void SetCurrentSection(LPCTSTR lpSection);
void SetCurrentFile(LPCTSTR lpFile);
LPCTSTR GetCurrentSection();
LPCTSTR GetCurrentFile();
protected:
TCHAR m_strSection[MAX_SECTIONNAME_SIZE];
TCHAR m_strFile[MAX_PATH];
};
代码: