
unit FindFiles;

interface

uses
  SysUtils, Classes, RegExpr{, LazFileUtils};

procedure SearchFiles(AList: TStrings; const APath, AMask: string; const ASubDirs: boolean = FALSE);

implementation

procedure SearchFiles(AList: TStrings; const APath, AMask: string; const ASubDirs: boolean);
var
  LExpr: TRegExpr;
  
  procedure Search(const APath2: string);
  var
    LRec: TSearchRec;
  begin
    if FindFirst{UTF8}(
      Concat(IncludeTrailingPathDelimiter(APath2), '*'),
      faAnyFile or faDirectory,
      LRec
    ) = 0 then
    begin
      repeat
        if (LRec.Attr and faDirectory) = faDirectory then
        begin
          if ASubDirs and (LRec.Name <> '.') and (LRec.Name <> '..') then
            Search(Concat(IncludeTrailingPathDelimiter(APath2), LRec.Name))
        end else
          if LExpr.Exec(LRec.Name) then
          begin
            AList.Append(Concat(IncludeTrailingPathDelimiter(APath2), LRec.Name));
            //WriteLn(LRec.Name);
          end;
      until FindNext{UTF8}(LRec) <> 0;
      FindClose{UTF8}(LRec);
    end;
  end;

begin
  if not Assigned(AList) then
  begin
    WriteLn(ErrOutput, 'List not created.');
    Exit;
  end;
  
  LExpr := TRegExpr.Create(AMask);
  try
    LExpr.Exec('a');
  except
    on E: Exception do
    begin
      WriteLn(StdErr, E.Message);
      LExpr.Free;
      Exit;
    end;
  end;
  Search(APath);
  LExpr.Free;
end;

end.
