How Can I Efficiently Read The FIrst Few Lines of Many Files in Delphi

后端 未结 5 2075
清歌不尽
清歌不尽 2020-12-15 12:43

I have a \"Find Files\" function in my program that will find text files with the .ged suffix that my program reads. I display the found results in an explorer-like window t

5条回答
  •  渐次进展
    2020-12-15 12:56

    Sometimes oldschool pascal stylee is not that bad. Even though non-oo file access doesn't seem to be very popular anymore, ReadLn(F,xxx) still works pretty ok in situations like yours.

    The code below loads information (filename, source and version) into a TDictionary so that you can look it up easily, or you can use a listview in virtual mode, and look stuff up in this list when the ondata even fires.

    Warning: code below does not work with unicode.

    program Project101;
    {$APPTYPE CONSOLE}
    
    uses
      IoUtils, Generics.Collections, SysUtils;
    
    type
      TFileInfo=record
        FileName,
        Source,
        Version:String;
      end;
    
    function LoadFileInfo(var aFileInfo:TFileInfo):Boolean;
    var
      F:TextFile;
    begin
      Result := False;
      AssignFile(F,aFileInfo.FileName);
      {$I-}
      Reset(F);
      {$I+}
      if IOResult = 0 then
      begin
        ReadLn(F,aFileInfo.Source);
        ReadLn(F,aFileInfo.Version);
        CloseFile(F);
        Exit(True)
      end
      else
        WriteLn('Could not open ', aFileInfo.FileName);
    end;
    
    var
      FileInfo:TFileInfo;
      Files:TDictionary;
      S:String;
    begin
      Files := TDictionary.Create;
      try
        for S in TDirectory.GetFiles('h:\WINDOWS\system32','*.xml') do
        begin
          WriteLn(S);
          FileInfo.FileName := S;
          if LoadFileInfo(FileInfo) then
            Files.Add(S,FileInfo);
        end;
    
        // showing file information...
        for FileInfo in Files.Values do
          WriteLn(FileInfo.Source, ' ',FileInfo.Version);
      finally
        Files.Free
      end;
      WriteLn;
      WriteLn('Done. Press any key to quit . . .');
      ReadLn;
    end.
    

提交回复
热议问题