我把文件加载到一个二进制格式的数组,这似乎需要一段时间有没有更好的更快的比较有效的方式来做到这一点。我使用写回文件类似的方法。
程序打开文件(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文件快速读/写
发布评论