递归函数实例: 搜索当前目录下的所有嵌套目录
2010-12-17 11:21
225 查看
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.
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.
相关文章推荐
- 理解 Delphi 的类(十) - 深入方法[28] - 递归函数实例: 搜索当前目录下的所有嵌套目录
- 目录文件操作实例[2]_列出当前盘(驱动器)上的所有目录及文件
- dos下搜索当前目录及其子目录下的所有特定后缀名的文件并拷贝到新文件夹
- grep搜索当前目录下的所有文件的内容
- 搜索当前目录下所有文件包含某关键词的文本/文件名/行号
- 用嵌套递归的方法搜索指定目录下的所有文件
- 使用grep指令在当前目录下所有文件中搜索指定文本
- 去掉当前目录及其所有子目录下的svn目录
- 一点一点学写Makefile(2)-自动搜所当前目录下的所有源文件
- python获取当前目录路径和上级路径的实例
- php实例分享之通过递归实现删除目录下的所有文件详解
- PHP使用递归方式列出当前目录下所有文件的方法
- 列出zip文件内全部内容 当前目录下的所有文件压缩成zip格式的文件(file.zip)
- 搜索指定目录下的所有文件或者指定文件(可用于多级目录)
- find搜索目录下所有文件内容中的某个单词
- python文件和目录操作方法大全(含更改文件夹下所有文件名称的实例)
- 当前目录下所有代码中查找
- 如何touch一个目录及其下所有嵌套子目录中的文件?
- linux命令-查看当前目录下所有文件的大小:“ll -h”
- 一个搜索引擎搜索出来的目录与其内容不同步的实例终结篇