應用程式常需保存設定參數(如視窗位置、使用者偏好、連線字串),INI 檔案因結構簡單、易讀、無需資料庫引擎,仍是輕量級設定儲存的經典選擇。本文詳細說明以 Win32 API 操作 INI 的完整流程與常見陷阱。
WritePrivateProfileStringBOOL WritePrivateProfileString(
LPCTSTR lpAppName, // 區段名
LPCTSTR lpKeyName, // 鍵名
LPCTSTR lpString, // 字串值
LPCTSTR lpFileName // 完整 INI 路徑
);
lpAppName:區段名稱,對應 INI 中的 [SectionName]。lpKeyName:鍵名稱,區段下的變數名。lpString:字串值,需為 LPCTSTR 或 CString 型別。lpFileName:完整路徑,目錄必須預先存在。CString strName = _T("張三");
int nAge = 12;
CString strAge;
strAge.Format(_T("%d"), nAge);
::WritePrivateProfileString(_T("StudentInfo"), _T("Name"), strName, _T("C:\\Data\\student.ini"));
::WritePrivateProfileString(_T("StudentInfo"), _T("Age"), strAge, _T("C:\\Data\\student.ini"));
產生內容:
[StudentInfo]
Name=張三
Age=12
GetPrivateProfileString / GetPrivateProfileIntDWORD GetPrivateProfileString(
LPCTSTR lpAppName,
LPCTSTR lpKeyName,
LPCTSTR lpDefault, // 找不到時的預設值
LPTSTR lpReturnedString, // 接收緩衝區
DWORD nSize, // 緩衝區大小
LPCTSTR lpFileName
);
CString strName;
GetPrivateProfileString(_T("StudentInfo"), _T("Name"), _T("預設姓名"),
strName.GetBuffer(MAX_PATH), MAX_PATH, _T("C:\\Data\\student.ini"));
strName.ReleaseBuffer();
UINT GetPrivateProfileInt(
LPCTSTR lpAppName,
LPCTSTR lpKeyName,
INT nDefault,
LPCTSTR lpFileName
);
int nAge = GetPrivateProfileInt(_T("StudentInfo"), _T("Age"), 0, _T("C:\\Data\\student.ini"));
應用場景:記錄最近使用的檔案清單 (MRU)。
const int MAX_FILES = 6;
for (int i = 0; i < MAX_FILES; ++i) {
CString key; key.Format(_T("FileName%d"), i);
::WritePrivateProfileString(_T("RecentFiles"), key, fileList[i], iniPath);
}
::WritePrivateProfileString(_T("RecentFiles"), _T("Count"), _T("6"), iniPath);
int count = GetPrivateProfileInt(_T("RecentFiles"), _T("Count"), 0, iniPath);
for (int i = 0; i < count; ++i) {
CString key; key.Format(_T("FileName%d"), i);
CString path;
GetPrivateProfileString(_T("RecentFiles"), key, _T(""), path.GetBuffer(MAX_PATH), MAX_PATH, iniPath);
path.ReleaseBuffer();
// 使用 path...
}
lpFileName 必須為絕對路徑,且所有目錄層級必須存在,否則回傳 FALSE。\\,或使用正斜線 /(Win32 API 支援)。.\settings.ini 表示程式所在目錄。WritePrivateProfileStringW,字串常數加 _T() 或 L""。新專案建議考慮:
CFile/std::filesystem:結構化、跨平台、易序列化。HKLM。INI 檔案仍適合簡單、小型、人工可編輯的設定場景,掌握其 API 用法是 Windows 程式設計師的基本功。