記錄型檔案 (Record-based File) 是 Delphi 傳統的二進位資料儲存方式,結構類似「單表資料庫」,適用於簡單資料持久化場景。
| 特性 | 記錄型檔案 | 資料庫 |
|---|---|---|
| 本質 | 二進位檔案,類似記事本存結構體 | 專用儲存引擎,支援索引、查詢、事務 |
| 增刪改查 | 手動管理檔案指標,較麻煩 | SQL 語句,功能豐富 |
| 適用場景 | 單一結構、資料量小、無複雜查詢 | 多表關聯、大量資料、複雜查詢 |
| 部署 | 單一檔案,無引擎相依 | 需資料庫引擎或 DLL |
type
MyFile = record
name: string[20]; { 必須指定固定長度 }
sex: string[10]; { 必須指定固定長度 }
age: Integer;
end;
var
myselfFile: file of MyFile; { 記錄型檔案變數 }
mySelfInfo: MyFile; { 單筆記錄緩衝 }
{ 對記錄緩衝賦值 }
mySelfInfo.name := Edit1.Text;
mySelfInfo.sex := Edit2.Text;
mySelfInfo.age := StrToInt(Edit3.Text);
{ 對檔案操作 }
if SaveDialog1.Execute then
begin
AssignFile(myselfFile, SaveDialog1.FileName); { 檔案變數與磁碟檔案關聯 }
if FileExists(SaveDialog1.FileName) then
Reset(myselfFile) { 存在 → 唯讀開啟,指標在開頭 }
else
Rewrite(myselfFile); { 不存在 → 建立新檔,指標在開頭 }
Seek(myselfFile, FileSize(myselfFile)); { 移動指標到檔案末尾 (附加模式) }
Write(myselfFile, mySelfInfo); { 寫入記錄 }
CloseFile(myselfFile); { 關閉關聯,對應 AssignFile }
end;
Reset(myselfFile); { 唯讀開啟 }
while not Eof(myselfFile) do
begin
Read(myselfFile, mySelfInfo); { 讀取一筆記錄到緩衝 }
{ 顯示 mySelfInfo.name, sex, age }
end;
CloseFile(myselfFile);
輸入資料:
張某某 男 21
周某某 女 21
項某某 男 21
...
以文字編輯器開啟 (亂碼,因為是二進位):
張某某 男 & 周某某 女 & 項某某 男 & ...
關鍵:唯有使用 Read(myselfFile, mySelfInfo) 才能正確解析回結構體,文字編輯器無法直接閱讀。
| 函式 | 用途 | 關鍵行為 |
|---|---|---|
AssignFile | 關聯檔案變數與磁碟路徑 | 不建立檔案,僅建立關聯 |
Rewrite | 建立新檔/覆寫現有檔 | 指標在 0,檔案長度歸零 |
Reset | 唯讀開啟現有檔 | 指標在 0 |
Seek | 移動檔案指標 | Seek(f, FileSize(f)) 移到末尾 |
Write | 寫入記錄 | 依記錄大小寫入,指標後移 |
Read | 讀取記錄 | 依記錄大小讀取,指標後移 |
CloseFile | 關閉關聯 | 釋放檔案鎖定,配對 AssignFile |
https://7071976.blog.51cto.com/7061976/1208387
記錄型檔案是理解「結構體序列化」與「檔案指標操作」的最佳入門教材,雖然實務上多為 SQLite/JSON 取代,但其核心概念在嵌入式、遊戲存檔、高效能日誌等領域仍具價值。