在VC程式中利用系統提供的GetPrivateProfileString及WritePrivateProfileString函數直接讀寫系統配置ini檔案(指定目錄下的Ini檔案)
假設在目前的目錄下有一個檔案名稱為Tets.ini的檔案
用於儲存使用者名稱和密碼
檔案格式如下:
[Section1]
Item1=huzhifeng
Item2=1234565
1.寫INI檔案
void CINI_File_TestDlg::OnButtonWrite()
{
// TODO: Add your control notification handler code here
CString strSection = "Section1";
CString strSectionKey = "Item1";
char strBuff[256];
CString strValue = _T("");
CString strFilePath;
strFilePath=GetCurrentDirectory(256,strBuff); //擷取當前路徑
strFilePath.Format("%s\\Test.ini",strBuff);
GetDlgItemText(IDC_EDIT_NAME,strValue); //擷取文字框內容:即姓名
WritePrivateProfileString(strSection,strSectionKey,strValue,strFilePath); //寫入ini檔案中相應欄位
strSectionKey="Item2";
GetDlgItemText(IDC_EDIT_PASSWORD,strValue); //擷取文字框內容:即密碼
WritePrivateProfileString(strSection,strSectionKey,strValue,strFilePath);
}
2.讀INI檔案內容
void CINI_File_TestDlg::OnButtonRead()
{
// TODO: Add your control notification handler code here
CString strSection = "Section1";
CString strSectionKey = "Item1";
char strBuff[256];
CString strValue = _T("");
CString strFilePath;
strFilePath=GetCurrentDirectory(256,strBuff); //擷取當前路徑
strFilePath.Format("%s\\Test.ini",strBuff);
GetPrivateProfileString(strSection,strSectionKey,NULL,strBuff,80,strFilePath); //讀取ini檔案中相應欄位的內容
strValue=strBuff;
SetDlgItemText(IDC_EDIT_NAME,strValue);
strSectionKey="Item2";
GetPrivateProfileString(strSection,strSectionKey,NULL,strBuff,80,strFilePath);
strValue=strBuff;
SetDlgItemText(IDC_EDIT_PASSWORD,strValue);
UpdateData(FALSE);
}