在工程目录下有配置文件connconfig.ini,内容如下:
1 从ini文件获取配置信息
获取字符串数据使用GetPrivateProfileString,获取整形数据使用GetPrivateProfileInt,下面是微软官方API函数原型:
Note This function is provided only for compatibility with 16-bit Windows-based applications. Applications should store initialization information in the registry.
DWORD GetPrivateProfileString(
LPCTSTR lpAppName,
LPCTSTR lpKeyName,
LPCTSTR lpDefault,
LPTSTR lpReturnedString,
DWORD nSize,
LPCTSTR lpFileName
);
Note This function is provided only for compatibility with 16-bit Windows-based applications. Applications should store initialization information in the registry.
UINT GetPrivateProfileInt(
LPCTSTR lpAppName,
LPCTSTR lpKeyName,
INT nDefault,
LPCTSTR lpFileName
);
void GetUserConfig(CString fileName, int &id, CString &user, CString &password)
{
//配置文件在工程目录
CString strModule;
GetModuleFileName(NULL, strModule.GetBuffer(MAX_PATH), MAX_PATH);
//注:使用该API函数得到的是程序文件完整路径文件名,去掉文件名后才是路径。
strModule.ReleaseBuffer();
int pos = strModule.ReverseFind('\\');
CString strDir;
strDir = strModule.Left(pos);
if( strDir.Right(1) != "\\" )
{
strDir += "\\" ;
}
CString strIniDir = strDir + fileName;
int tempId=0;
char tempUser[MAX_PATH]={0};
char tempPassword[MAX_PATH]={0};
//获取int型数据
id = GetPrivateProfileInt(_T("UserInfo"), _T("id"),0,strIniDir);
//获取String型数据
GetPrivateProfileString(_T("UserInfo"), _T("user"),"",tempUser,MAX_PATH,strIniDir);
GetPrivateProfileString(_T("UserInfo"), _T("password"),"",tempPassword,MAX_PATH,strIniDir);
user = tempUser;
password = tempPassword;
}
使用示例:
CString configFile("connconfig.ini");
int id;
CString user;
CString password
GetUserConfig(configFile, id, user, password);
2 保存配置信息到ini文件
保存配置信息使用WritePrivateProfileString,既WritePrivateProfileStringA
Note This function is provided only for compatibility with 16-bit versions of Windows. Applications should store initialization information in the registry.
BOOL WritePrivateProfileStringA(
LPCSTR lpAppName,
LPCSTR lpKeyName,
LPCSTR lpString,
LPCSTR lpFileName
);
void SaveUserConfig(CString fileName, int &id, CString &user, CString &password)
{
//配置文件在工程目录
CString strModule;
GetModuleFileName(NULL, strModule.GetBuffer(MAX_PATH), MAX_PATH);
//注:使用该API函数得到的是程序文件完整路径文件名,去掉文件名后才是路径。
strModule.ReleaseBuffer();
int pos = strModule.ReverseFind('\\');
CString strDir;
strDir = strModule.Left(pos);
if( strDir.Right(1) != "\\" )
{
strDir += "\\" ;
}
CString strIniDir = strDir + fileName;
//将int数据转为Cstring类型
CString idStr;
idStr.Format("%d",type);
WritePrivateProfileString(_T("UserInfo"), _T("id"),id.GetBuffer(0),strIniDir);
WritePrivateProfileString(_T("UserInfo"), _T("user"),user.GetBuffer(0),strIniDir);
WritePrivateProfileString(_T("UserInfo"), _T("password"),password.GetBuffer(0),strIniDir);
}
使用示例:
CString configFile("connconfig.ini");
int id = 100;
CString user = "bob";
CString password = "123456";
SaveUserConfig(configFile, id, user, password);