gpt4 book ai didi

delphi - delphi中的文件快速读/写

转载 作者:行者123 更新时间:2023-12-03 14:44:40 32 4
gpt4 key购买 nike

我正在以二进制形式将文件加载到数组中,这似乎需要一段时间有没有更好更快更有效的方法来做到这一点。我正在使用类似的方法写回文件。

procedure openfile(fname:string);
var
myfile: file;
filesizevalue,i:integer;
begin
assignfile(myfile,fname);
filesizevalue:=GetFileSize(fname); //my method
SetLength(dataarray, filesizevalue);
i:=0;
Reset(myFile, 1);
while not Eof(myFile) do
begin
BlockRead(myfile,dataarray[i], 1);
i:=i+1;
end;
CloseFile(myfile);
end;

最佳答案

如果你真的想快速读取二进制文件,让 Windows 担心缓冲;-) 通过使用 Memory Mapped Files 。使用它,您可以简单地将文件映射到内存位置并像数组一样读取。

你的函数将变成:

procedure openfile(fname:string);
var
InputFile: TMappedFile;
begin
InputFile := TMappedFile.Create;
try
InputFile.MapFile(fname);
SetLength(dataarray, InputFile.Size);
Move(PByteArray(InputFile.Content)[0], Result[0], InputFile.Size);
finally
InputFile.Free;
end;
end;

但我建议不要使用全局变量dataarray,而是将其作为参数中的 var 传递,或者使用返回结果数组的函数。

procedure ReadBytesFromFile(const AFileName : String; var ADestination : TByteArray);
var
InputFile : TMappedFile;
begin
InputFile := TMappedFile.Create;
try
InputFile.MapFile(AFileName);
SetLength(ADestination, InputFile.Size);
Move(PByteArray(InputFile.Content)[0], ADestination[0], InputFile.Size);
finally
InputFile.Free;
end;
end;

TMappedFile 来 self 的文章 Fast reading of files using Memory Mapping ,本文还包含如何将其用于更“高级”二进制文件的示例。

关于delphi - delphi中的文件快速读/写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/455790/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com