|
//读写INI文件方法
BOOL CBaseWnd::WriteMyProfileString(const CString strSection, const CString strEntry, const CString strValue, const CString strIniPath)
{
if(strSection == L"" || strEntry == L"" || strValue == L"" || strIniPath == L"")
{
return FALSE;
}
CFile IniFile;
CString strCombine;
TRY
{
if(! IniFile.Open(strIniPath, CFile::modeReadWrite|CFile::modeCreate|CFile::modeNoTruncate))
{
return FALSE;
}
if(IniFile.GetLength() == 0)
{
strCombine = L"[" + strSection + L"]" + L"\r\n"
+ strEntry + L"=" + strValue + L"\r\n";
LPTSTR lpCombine = strCombine.GetBuffer(0);
IniFile.Write(lpCombine, strCombine.GetLength() * 2);
IniFile.Close();
return TRUE;
}
WCHAR *pBuf;
pBuf = new WCHAR[IniFile.GetLength() / 2 + 1];
if(pBuf == NULL)
{
IniFile.Close();
return FALSE;
}
if(IniFile.Read(pBuf, IniFile.GetLength()) != IniFile.GetLength())
{
delete[] pBuf;
IniFile.Close();
return FALSE;
}
pBuf[IniFile.GetLength() / 2] = NULL;
strCombine.GetBuffer(MAX_LEN);
strCombine = pBuf;
delete[] pBuf;
int iIndex1, iIndex2, iIndex3, iIndexT;
iIndex1 = strCombine.Find(L"[" + strSection + L"]\r\n");
if(iIndex1 == -1)
{
strCombine += L"[" + strSection + L"]" + L"\r\n"
+ strEntry + L"=" + strValue + L"\r\n";
LPTSTR lpCombine = strCombine.GetBuffer(0);
IniFile.SetLength(0);
IniFile.SeekToBegin();
IniFile.Write(lpCombine, strCombine.GetLength() * 2);
IniFile.Close();
return TRUE;
}
iIndexT = iIndex1 + 4 + strSection.GetLength();
iIndex2 = strCombine.Find(strEntry + L"=", iIndexT);
if(iIndex2 == -1)
{
strCombine.Insert(iIndexT, strEntry + L"=" + strValue + L"\r\n");
LPTSTR lpCombine = strCombine.GetBuffer(0);
IniFile.SetLength(0);
IniFile.SeekToBegin();
IniFile.Write(lpCombine, strCombine.GetLength() * 2);
IniFile.Close();
return TRUE;
}
else
{
iIndex3 = strCombine.Find(L"\r\n", iIndex2 + 1);
if(iIndex3 == -1)
{
IniFile.Close();
return FALSE;
}
iIndexT = iIndex2 + 1 + strEntry.GetLength();
strCombine.Delete(iIndexT, iIndex3 - iIndexT);
strCombine.Insert(iIndexT, strValue);
LPTSTR lpCombine = strCombine.GetBuffer(0);
IniFile.SetLength(0);
IniFile.SeekToBegin();
IniFile.Write(lpCombine, strCombine.GetLength() * 2);
IniFile.Close();
return TRUE;
}
}
CATCH(CFileException, e)
{
}
END_CATCH
IniFile.Close();
return FALSE;
} |
|