文件历遍看搜索主要用二个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,地到所有目录都被查到为止.我们单步执行调试,可以完整的看到整个过程!