从Delphi文件快速读/写

编程入门 行业动态 更新时间:2024-10-23 03:23:03
本文介绍了从Delphi文件快速读/写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我把文件加载到一个二进制格式的数组,这似乎需要一段时间有没有更好的更快的比较有效的方式来做到这一点。我使用写回文件类似的方法。

程序打开文件(FNAME:字符串);VAR    MYFILE:文件;    filesizevalue,我:整数;开始  assignfile(MYFILE,FNAME);  filesizevalue:= GetFileSize(FNAME); //我的方法  SetLength函数(DataArray中,filesizevalue);  I:= 0;  复位(MYFILE,1);  虽然没有EOF(MYFILE)做    开始      BlockRead(MYFILE,DataArray中[I],1);      I:= I + 1;    结束;  CloseFile(MYFILE);结束;

解决方案

您一般不应读取文件逐字节。使用BlockRead有一个较大的值(512或1024常常是最好的),并使用其返回值,找出了多少字节被读取。

如果规模不是太大(和你的SetLength函数的使用似乎支持这一点),你也可以使用一个BlockRead调用读取完整的文件一次。所以,修改的方法,这将是:

AssignFile(MYFILE,FNAME);filesizevalue:= GetFileSize(FNAME);复位(MYFILE,1);SetLength函数(DataArray中,filesizevalue);BlockRead(MYFILE,DataArray中[0],filesizevalue);CloseFile(MYFILE);

也许你也可以改变程序名为OpenAndReadFile一个布尔函数返回false,如果该文件无法打开或读取。

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;

解决方案

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.

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);

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文件快速读/写

本文发布于:2023-11-11 06:16:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1577604.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:速读   文件   Delphi

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!