In-depth method (28)-recursive function example: search all nested directories under the current directory

// The above example cannot explain the essence of recursive function, just come to a practical function, just use it. 

Unit Unit1; interface uses 
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, 
  Dialogs, StdCtrls; type 
  TForm1 = class (TForm) 
    Button1: TButton; 
    Memo1: TMemo; procedure Button1Click (Sender: TObject);
   end ; var 
  Form1: TForm1; implementation {$ R * .dfm} // List all directories under a directory (including nesting ) Function procedure GetDirs (dirName: string ; List: TStrings);
 var 
  SRec: TSearchRec;             {define TSearchRec structure variable} 
  dir:






    








string ;
 const 
  attr: Integer = faDirectory; {File attribute constant, which means this is a folder} 
begin 
  dirName: = ExcludeTrailingBackslash (dirName) + '\' ; {I don't know if it is the last one; remove it first, then add} 
  dir: = dirName + '*. *' ; {plus \; *. * or * means all files, the system will treat the directory as a file} 

  if FindFirst (dir, attr, SRec) = 0  then  {start searching, and Give information to SRec, return 0 to find the first one} 
  begin 
    repeat 
      if (SRec.Attr = attr) and               {if it is a folder} 
         (SRec.Name <> '.' ) And               {exclude the upper directory} 
         (SRec.Name <> '..' ) then             {exclude root directory}
       begin 
         List.Add (dirName + SRec.Name);       {Record the result with List} 
         GetDirs (dirName + SRec.Name, List); {This sentence is a recursive call, if there is no sentence, you can only search the current directory} 
       end ;
     until (FindNext (SRec) <> 0 );                 {Find next, return 0 means found} 
  end ;

  FindClose (SRec);                            {End search} 
end ; {Test} procedure TForm1.Button1Click (Sender: TObject);
 var 
  list: TStrings; begin 
  list: = TStringList.Create;
  GetDirs ( 'C: \ Downloads' , list);
  Memo1.Lines: = list;
  list.Free; end ;










end.

Guess you like

Origin www.cnblogs.com/fansizhe/p/12729746.html