文件历遍搜索详解

文件历遍看搜索主要用二个Windows API,分别是 FindFirst 和FindNext.他们的返回类

型为TSearchRec

TSearchRec结构:

TSearchRec = record
   Time: Integer;
   Size: Integer;
   Attr: Integer;
   Name: TFileName;
   ExcludeAttr: Integer;
   FindHandle: THandle;
   FindData: TWin32FindData;
end;

其中Size表示文件的大小,Name是文件的名称;Attr是文件的属性,Time包括创建和修改文件的时间;

Attr 属性有 faReadOnly(只读文件),faHidden(隐藏),faSysFile(系统),aVolumeID(卷标),faDirectory(文件夹),faArchive(存档),faAnyFile(任何).

下面是详细代码:

unit SearchFUnit;

interface

uses
  SysUtils, Classes;

  procedure FindFile(APath, FName: String;FList: TStrings);
  procedure GetDirectoryName(Dir: String): String;
  function IsDirNotation(ADirName: String): Boolean;

implementation

procedure FindFile(APath, FName: String;FList: TStrings);
var
  FSearchRec,
  DSearchRec: TSearchRec;
  FindResult: integer;
begin
    APath := GetDirectoryName(APath);
    FindResult := FindFirst(APath + AName,faAnyFile + faHidden +
                  faSysFile + faReadOnly,FSearchRec);
    try
      while FindResult = 0 do
      begin
          FList.Add(APath + FSearchRec.Name);
        FindResult := FindNext(FSearchRec);
      end;

      FindResult := FindFirst(APath + '*.*',faDirectory,DSearchRec);

      while FindResult = 0 do
      begin
        if ((DSearchRec.Attr and faDirectory) = faDirectory) and not
            isDirNOtation(DSearchRec.Name) then
          FindFile(APath + DSearchRec.Name,FName, FList);
        FindResult := FindNext(DSearchRec);
      end;
    finally
      FindClose(FSearchRec);
    end;
end;

function GetDirectoryName(Dir: String): String;
begin
  if Dir[Length(Dir)] <> '/' then
    Result := Dir + '/'
  else
    Result := Dir;
end;

function IsDirNotation(ADirName: String): Boolean;
begin
  Result := (ADirName = '.') or (ADirName = '..');
end;

end.

 在这个方法中,通过第一个while..do循环在参数Apath指定的目录下进行查找,找到并添加到FList中,在第二个while..do循环是对指定目录的字目录进行查找,利用得到的子目录依次作为APath参数,递归调用FindFile,地到所有目录都被查到为止.

 在这个方法中,通过第一个while..do循环在参数Apath指定的目录下进行查找,找到并添加到FList中,在第二个while..do循环是对指定目录的字目录进行查找,利用得到的子目录依次作为APath参数,递归调用FindFile,地到所有目录都被查到为止.

我们单步执行调试,可以完整的看到整个过程!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值