zoukankan      html  css  js  c++  java
  • 理解 Delphi 的类(十) 深入方法[28] 递归函数实例: 搜索当前目录下的所有嵌套目录

    //上面一个例子不能说明递归函数的本质, 直接来个实用的函数吧, 刚好要用.
    
    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}
    
    //列出一个目录下所有目录(包括嵌套)的函数
    procedure GetDirs(dirName: string; List: TStrings);
    var
      SRec: TSearchRec;            {定义 TSearchRec 结构变量}
      dir: string;
    const
      attr: Integer = faDirectory; {文件属性常量, 表示这是文件夹}
    begin
      dirName := ExcludeTrailingBackslash(dirName) + '\'; {不知道最后是不是 \; 先去掉, 再加上}
      dir := dirName + '*.*'; {加上 \; *.* 或 * 表示所有文件, 系统会把目录也当作一个文件}
    
      if FindFirst(dir, attr, SRec) = 0 then {开始搜索,并给 SRec 赋予信息, 返回0表示找到第一个}
      begin
        repeat
          if (SRec.Attr = attr) and              {如果是文件夹}
             (SRec.Name <> '.') and              {排除上层目录}
             (SRec.Name <> '..') then            {排除根目录}
           begin
             List.Add(dirName + SRec.Name);      {用List记下结果}
             GetDirs(dirName + SRec.Name, List); {这句就是递归调用, 如果没有这句, 只能搜索当前目录}
           end;
        until(FindNext(SRec)<>0);                {找下一个, 返回0表示找到}
      end;
    
      FindClose(SRec);                           {结束搜索}
    end;
    
    
    
    {测试}
    procedure TForm1.Button1Click(Sender: TObject);
    var
      list: TStrings;
    begin
      list := TStringList.Create;
    
      GetDirs('C:\Downloads', list);
      Memo1.Lines := list;
    
      list.Free;
    end;
    
    end.
    
  • 相关阅读:
    xcode 工具栏中放大镜的替换的说明
    xcode 工具栏中放大镜的替换的简单说明
    xcode 资源管理
    泛型的冒泡,插入,选择,希尔算法
    一套手写ajax加一般处理程序的增删查改
    Android自定义控件_自绘控件
    查看自己Android设备分辨率
    Collection集合 和 Map
    深入理解Java中的面向对象
    webserivce请求头组装
  • 原文地址:https://www.cnblogs.com/del/p/1039932.html
Copyright © 2011-2022 走看看