首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >高效地将文件读入Pascal AnsiString

高效地将文件读入Pascal AnsiString
EN

Stack Overflow用户
提问于 2016-12-30 10:16:04
回答 1查看 1.5K关注 0票数 0

我使用此代码将文件内容读取到AnsiString变量中。

代码语言:javascript
复制
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

EN

回答 1

Stack Overflow用户

发布于 2016-12-30 11:47:28

代码语言:javascript
复制
        begin
            read(f,c);
            s:=s+c;
        end;

您正在读取字符/字符并将其追加到字符串中,这就是您的程序运行缓慢的原因。在单个变量中读取整个文件是不符合逻辑。使用buffer存储文件读取的内容,然后对其进行处理,并释放缓冲区以供下一次读取输入。

代码语言:javascript
复制
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上有更多示例

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41389750

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档