有效地将文件读入Pascal AnsiString

时间:2016-12-30 02:16:04

标签: pascal lazarus freepascal

我有这段代码将文件内容读取到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

1 个答案:

答案 0 :(得分:1)

        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.   

更多例子 File Handling in Pascal