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

Delphi 記錄數組文件存取:寫入與讀取完整實現

     編輯:Delphi

記錄定義

type
  TRecord = record
    Name: string[10];
    Address: string[50];
  end;
  TRecordFile = file of TRecord;

寫入函數:追加模式

function RecordsSaveToFile(aFileName: string; aRecord: TRecord): Boolean;
var
  RecFile: TRecordFile;
begin
  Result := False;
  AssignFile(RecFile, aFileName);
  FileMode := 2; // 讀寫
  if not FileExists(aFileName) then
    Rewrite(RecFile)
  else
    Reset(RecFile);
  try
    Seek(RecFile, FileSize(RecFile)); // 定位到末尾
    Write(RecFile, aRecord);
    Result := True;
  finally
    CloseFile(RecFile);
  end;
end;

讀取函數:順序讀取所有記錄

function RecordsLoadFromFile(aFileName: string): Boolean;
var
  RecFile: TRecordFile;
  aRecord: TRecord;
  RecCount, i: Integer;
begin
  Result := False;
  if not FileExists(aFileName) then Exit;
  AssignFile(RecFile, aFileName);
  FileMode := 2;
  Reset(RecFile);
  try
    RecCount := FileSize(RecFile);
    for i := 0 to RecCount - 1 do
    begin
      Seek(RecFile, i);
      Read(RecFile, aRecord);
      Form1.Memo1.Lines.Add(aRecord.Name + '=' + aRecord.Address);
    end;
    Result := True;
  finally
    CloseFile(RecFile);
  end;
end;

測試代碼

procedure TForm1.Button1Click(Sender: TObject); // 寫入 10 條
var
  aRecord: TRecord;
  i: Integer;
begin
  for i := 0 to 9 do
  begin
    aRecord.Name := 'aName' + IntToStr(i);
    aRecord.Address := '1234asdfssdf' + IntToStr(i);
    RecordsSaveToFile('c:\PersonS.dat', aRecord);
  end;
end;

procedure TForm1.Button2Click(Sender: TObject); // 讀取顯示
begin
  RecordsLoadFromFile('c:\PersonS.dat');
end;

注意事項

  • 記錄包含定長字符串 (string[10]),文件結構固定,便於隨機訪問。
  • FileMode := 2 表示讀寫共享,避免多進程衝突可加鎖。
  • 大量數據建議使用 TFileStream + 緩衝區提升性能。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved