我正在以二进制形式将文件加载到数组中,这似乎需要一段时间有没有更好更快更有效的方法来做到这一点.我正在使用类似的方法写回文件.
I am loading a file into a array in binary form this seems to take a while is there a better faster more efficent way to do this. i am using a similar method for writing back to the file.
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; 推荐答案您通常不应该逐字节读取文件.使用具有较大值的 BlockRead(通常最好使用 512 或 1024)并使用其返回值来确定读取了多少字节.
You generally shouldn't read files byte for byte. Use BlockRead with a larger value (512 or 1024 often are best) and use its return value to find out how many bytes were read.
如果大小不是太大(并且您对 SetLength 的使用似乎支持这一点),您还可以使用一个 BlockRead 调用一次读取完整的文件.所以,修改你的方法,这将是:
If the size isn't too large (and your use of SetLength seems to support this), you can also use one BlockRead call reading the complete file at once. So, modifying your approach, this would be:
AssignFile(myfile,fname); filesizevalue := GetFileSize(fname); Reset(myFile, 1); SetLength(dataarray, filesizevalue); BlockRead(myFile, dataarray[0], filesizevalue); CloseFile(myfile);也许您也可以将过程更改为名为 OpenAndReadFile 的布尔函数,如果无法打开或读取文件,则返回 false.
Perhaps you could also change the procedure to a boolean function named OpenAndReadFile and return false if the file couldn't be opened or read.
更多推荐
在delphi中快速读取/写入文件
发布评论