萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Delphi 控制 INI 檔案完整範例:讀寫字串與整數

Windows API 核心函數

Delphi 透過 GetPrivateProfileString、GetPrivateProfileInt、WritePrivateProfileString、WritePrivateProfileSection 操作 INI 檔,需在 uses 子句引入 Windows 單元。

讀取字串

var
  strResult: PChar;
begin
  GetPrivateProfileString(
    'windows',        // 區段名
    'NullPort',       // 鍵名
    'NIL',            // 預設值
    strResult,        // 接收緩衝區
    100,              // 緩衝區大小
    'c:\forwin95\win.ini' // INI 路徑
  );
  Edit1.Text := strResult;
end;

讀取整數

Edit1.Text := IntToStr(GetPrivateProfileInt(
  'intl',             // 區段名
  'iCountry',         // 鍵名
  0,                  // 預設值
  'c:\forwin95\win.ini' // INI 路徑
));

寫入字串

WritePrivateProfileString(
  'windows',          // 區段名
  'load',             // 鍵名
  'accca',            // 寫入值
  'c:\forwin95\win.ini' // INI 路徑
);

寫入整數(實為寫入鍵值對字串)

WritePrivateProfileSection(
  'windows',          // 區段名
  'read=100',         // 完整 "Key=Value" 字串
  'c:\forwin95\win.ini' // INI 路徑
);

實務提醒

  • 路徑建議使用完整絕對路徑,避免工作目錄變更導致讀寫失敗。
  • GetPrivateProfileString 的緩衝區需預先配置足夠大小(如 SetLength(strResult, 255))。
  • 寫入整數實質是寫入 Key=Value 字串,讀取時仍用 GetPrivateProfileInt 自動轉型。
  • VCL 也提供 TIniFile / TMemIniFile 封裝類,操作更物件導向、支援 Unicode,新專案建議優先使用。
copyright © 萬盛學電腦網 all rights reserved