Delphi: Alternative to using Reset/ReadLn for text file reading

后端 未结 7 1229
时光取名叫无心
时光取名叫无心 2020-12-14 11:10

i want to process a text file line by line. In the olden days i loaded the file into a StringList:

slFile := TStringList.Create();
slFile.LoadFr         


        
7条回答
  •  情书的邮戳
    2020-12-14 11:51

    I had same problem a few years ago especially the problem of locking the file. What I did was use the low level readfile from the shellapi. I know the question is old since my answer (2 years) but perhaps my contribution could help someone in the future.

    const
      BUFF_SIZE = $8000;
    var
      dwread:LongWord;
      hFile: THandle;
      datafile : array [0..BUFF_SIZE-1] of char;
    
    hFile := createfile(PChar(filename)), GENERIC_READ, FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING, FILE_ATTRIBUTE_READONLY, 0);
    SetFilePointer(hFile, 0, nil, FILE_BEGIN);
    myEOF := false;
    try
      Readfile(hFile, datafile, BUFF_SIZE, dwread, nil);   
      while (dwread > 0) and (not myEOF) do
      begin
        if dwread = BUFF_SIZE then
        begin
          apos := LastDelimiter(#10#13, datafile);
          if apos = BUFF_SIZE then inc(apos);
          SetFilePointer(hFile, aPos-BUFF_SIZE, nil, FILE_CURRENT);
        end
        else myEOF := true;
        Readfile(hFile, datafile, BUFF_SIZE, dwread, nil);
      end;
    finally
       closehandle(hFile);
    end;
    

    For me the speed improvement appeared to be significant.

提交回复
热议问题