CString strValue;
::GetPrivateProfileString(_T("Section"), _T("Key"), _T(""),
strValue.GetBuffer(MAX_PATH), MAX_PATH, _T(".\\Config.ini"));
// strValue 此時長度為 0,內容為空!
CString::GetBuffer(n) 回傳內部緩衝區指標並鎖定內容長度為 n,但 CString 物件本身的長度(GetLength())仍為 0。Windows API 寫入緩衝區後,CString 不知道資料已更新,導致後續操作(賦值、比較、operator LPCTSTR())讀到空字串。
CString strValue;
LPTSTR pBuf = strValue.GetBuffer(MAX_PATH);
::GetPrivateProfileString(_T("Section"), _T("Key"), _T(""),
pBuf, MAX_PATH, _T(".\\Config.ini"));
strValue.ReleaseBuffer(); // 關鍵:通知 CString 更新長度
// 現在 strValue 正常可用
BOOL ReadIniString(LPCTSTR section, LPCTSTR key, LPCTSTR def,
CString& outStr, LPCTSTR iniPath)
{
const int BUFSIZE = 1024;
LPTSTR buf = outStr.GetBuffer(BUFSIZE);
DWORD len = GetPrivateProfileString(section, key, def, buf, BUFSIZE, iniPath);
outStr.ReleaseBuffer();
return (len > 0);
}
// 使用
CString userName;
ReadIniString(_T("Custom"), _T("UserName"), _T(""), userName, _T(".\\Config.ini"));
GetWindowsDirectory, GetSystemDirectory, GetModuleFileNameFormatMessage (配合 FORMAT_MESSAGE_FROM_SYSTEM)LPTSTR lpBuffer, DWORD nSize 的輸出字串 APIGetBuffer 可選參數指定最小長度;若原配置不足會自動重新配置。ReleaseBuffer 可選參數指定實際長度(-1 表以 null 結尾計算)。GetBuffer/ReleaseBuffer 之間對同一 CString 進行其他操作(如賦值、連接),否則行為未定義。