我们在编写程序的过程中,要保存一些用户的设置信息。怎么才能方便的保存和读取呢?

一般我们保存信息由两个地方:1。注册表 

                                           2。ni文件

其实在vc中他们的实现都是一样哦。

  在应用程序类下的      * App::InitInstance()函数里加入下面的程序语句;

#ifdef  使用ini文件保存

char czProgName[MAX_PATH];

CString czN;

int  iNiValue=0;

//GetModuleFileName()得到程序的路径及名称

iNiValue= GetModuleFileName(0,czProgName,MAX_PATH);

czProgName[strlen(czProgName)-3] = '\0'; 

strcat(czProgName,"ini"); //我们的ini文件名是跟程序同名的,只是后缀不同

free((void*) m_pszProfileName);

m_pszProfileName =_tcsdup(_T(czProgName));

#else //使用注册表文件来保存

free((void*)m_pszRegistryKey);

m_pszRegistryKey = “My test App”;

#endif

加入上面的语句以后,我们就可以在需要的地方直接用:

当然在使用的时候要定义:  

CWinApp* theApp = NULL;

theApp = AfxGetApp();

theApp ->WriteProfileString( , ,)函数写入ini文件.

在需要读写的地方直接用  :

UINT GetProfileInt(LPCTSTR lpszSection, LPCTSTR lpszEntry, int nDefault);

BOOL WriteProfileInt(LPCTSTR lpszSection, LPCTSTR lpszEntry, int nValue);

当然在读取整数的时候,我们可以分别用

CString GetProfileString(LPCTSTR lpszSection, LPCTSTR lpszEntry,
            LPCTSTR lpszDefault = NULL);

BOOL WriteProfileString(LPCTSTR lpszSection, LPCTSTR lpszEntry,
            LPCTSTR lpszValue);

读取二进制数值时候用如下:

BOOL GetProfileBinary(LPCTSTR lpszSection, LPCTSTR lpszEntry,
            LPBYTE* ppData, UINT* pBytes);

BOOL WriteProfileBinary(LPCTSTR lpszSection, LPCTSTR lpszEntry,
            LPBYTE pData, UINT nBytes);

具体请参考MFC下面的APPUI3.cpp