我使用此代码将文件内容读取到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;这段代码运行非常慢。我有一个1MB的文件,程序运行了大约27秒。
如何更快地将文件内容读取到AnsiString?
发布于 2016-12-30 11:47:28
begin
read(f,c);
s:=s+c;
end;您正在读取字符/字符并将其追加到字符串中,这就是您的程序运行缓慢的原因。在单个变量中读取整个文件是不符合逻辑。使用buffer存储文件读取的内容,然后对其进行处理,并释放缓冲区以供下一次读取输入。
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. 在File Handling in Pascal上有更多示例
https://stackoverflow.com/questions/41389750
复制相似问题