首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> VC >> VC 教學

Visual C++ INI 檔案讀寫完整教學

     編輯:VC 教學

應用程式常需保存設定參數(如視窗位置、使用者偏好、連線字串),INI 檔案因結構簡單、易讀、無需資料庫引擎,仍是輕量級設定儲存的經典選擇。本文詳細說明以 Win32 API 操作 INI 的完整流程與常見陷阱。

一、寫入資料:WritePrivateProfileString

函式原型

BOOL 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 / GetPrivateProfileInt

字串讀取

DWORD 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...
}

四、關鍵注意事項(避坑指南)

  1. 完整路徑:lpFileName 必須為絕對路徑,且所有目錄層級必須存在,否則回傳 FALSE。
  2. 路徑分隔符:C++ 字串中反斜線需轉義 \\,或使用正斜線 /(Win32 API 支援)。
  3. 相對路徑:可用 .\settings.ini 表示程式所在目錄。
  4. Unicode/ANSI:專案設定為 Unicode 時,API 會對應 WritePrivateProfileStringW,字串常數加 _T() 或 L""。
  5. 效能考量:頻繁讀寫建議快取於記憶體,程式結束時一次寫入;或改用 Registry / XML / SQLite。

五、現代替代方案

新專案建議考慮:

  • JSON + CFile/std::filesystem:結構化、跨平台、易序列化。
  • Windows Registry:適合系統層級設定,但需管理員權限寫入 HKLM。
  • SQLite:需查詢、關聯、大量資料時的最佳選擇。

INI 檔案仍適合簡單、小型、人工可編輯的設定場景,掌握其 API 用法是 Windows 程式設計師的基本功。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved