[英]Read file into Pascal AnsiString efficiently [closed]
我有这段代码可以将文件内容读取到AnsiString
变量中。
var
c:char;
f:file of char;
s:ansistring;
begin
assign(f,'file');
reset(f);
s:='';
while not eof(f) do
begin
read(f,c);
s:=s+c;
end;
close(f);
end;
这段代码运行非常缓慢。 我有一个1 MB的文件,程序运行了大约27秒。
如何更快地将文件内容读取到AnsiString
?
begin
read(f,c);
s:=s+c;
end;
您正在读取字符/字符并附加字符串,这就是您的程序运行缓慢的原因。 用单个变量读取整个文件是不合逻辑的。 使用缓冲区存储读取的文件内容,然后对其进行处理并释放缓冲区以供下一次读取输入。
program ReadFile;
uses
Sysutils, Classes;
const
C_FNAME = 'C:\textfile.txt';
var
tfIn: TextFile;
s: string;
Temp : TStringList;
begin
// Give some feedback
writeln('Reading the contents of file: ', C_FNAME);
writeln('=========================================');
Temp := TStringList.Create;
// Set the name of the file that will be read
AssignFile(tfIn, C_FNAME);
// Embed the file handling in a try/except block to handle errors gracefully
try
// Open the file for reading
reset(tfIn);
// Keep reading lines until the end of the file is reached
while not eof(tfIn) do
begin
readln(tfIn, s);
Temp.Append(s);
end;
// Done so close the file
CloseFile(tfIn);
writeln(temp.Text);
except
on E: EInOutError do
writeln('File handling error occurred. Details: ', E.Message);
end;
//done clear the TStringList
temp.Clear;
temp.Free;
// Wait for the user to end the program
writeln('=========================================');
writeln('File ', C_FNAME, ' was probably read. Press enter to stop.');
readln;
end.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.