類型定義
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。