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

Delphi 動態整數數組文件存取:寫入與讀取

     編輯:Delphi

類型定義

type
  TIntArray = array of Integer;

寫入函數:追加模式

function IntArrToFile(ns: TIntArray; FileName: string): Boolean;
var
  IntFile: file of Integer;
  n: Integer;
begin
  Result := False;
  AssignFile(IntFile, FileName);
  if FileExists(FileName) then Reset(IntFile) else Rewrite(IntFile);
  try
    Seek(IntFile, FileSize(IntFile)); // 定位末尾
    for n in ns do Write(IntFile, n);
    Result := True;
  finally
    CloseFile(IntFile);
  end;
end;

讀取函數:動態擴展數組

function FileToIntArr(FileName: string; var ns: TIntArray): Integer;
var
  IntFile: file of Integer;
begin
  Result := 0;
  if not FileExists(FileName) then Exit;
  AssignFile(IntFile, FileName);
  Reset(IntFile);
  try
    while not Eof(IntFile) do
    begin
      SetLength(ns, Length(ns) + 1);
      Read(IntFile, ns[High(ns)]);
    end;
    Result := Length(ns);
  finally
    CloseFile(IntFile);
  end;
end;

測試代碼

procedure TForm1.Button1Click(Sender: TObject); // 寫入
var
  IntArr: TIntArray;
begin
  SetLength(IntArr, 3);
  IntArr[0] := 111;
  IntArr[1] := 222;
  IntArr[2] := 333;
  IntArrToFile(IntArr, 'c:\temp\test.num');
end;

procedure TForm1.Button2Click(Sender: TObject); // 讀取顯示
var
  IntArr: TIntArray;
  n: Integer;
begin
  FileToIntArr('c:\temp\test.num', IntArr);
  for n in IntArr do ShowMessage(IntToStr(n));
end;

優化建議

  • 大量數據用 BlockWrite/BlockRead + 緩衝區減少系統調用。
  • 讀取前預估大小 SetLength(ns, FileSize(IntFile) div SizeOf(Integer)) 避免多次擴容。
  • 跨平台建議使用 TFileStream + TBytes。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved