以下代码列出文件但不列出目录
var
rec : tsearchrec;
begin
findfirst('c:\test\*',faanyfile-fadirectory,rec);
showmessage(rec.Name);
if findnext(rec) <> 0 then close else
showmessage (rec.Name);
end;
Run Code Online (Sandbox Code Playgroud)
Fra*_*ois 18
Run Code Online (Sandbox Code Playgroud)var rec : tsearchrec; begin if FindFirst('c:\*', faAnyFile, rec) = 0 then begin repeat ShowMessage(rec.Name); until FindNext(rec) <> 0; FindClose(rec); end; end;
除了所有普通文件外, Attr参数还指定要包含的特殊文件.
换句话说,FindFirst()无论您指定的任何过滤条件如何,始终返回普通文件.该Attr参数仅包括基本过滤器中的其他类型的属性.您需要测试该TSearchRec.Attr字段以确定报告的条目实际上是文件还是目录,例如:
if (rec.Attr and faDirectory) <> 0 then
// item is a directory
else
// item is a file
Run Code Online (Sandbox Code Playgroud)
如果实现递归搜索循环,请确保忽略".".和".."目录,否则你的循环将无限递归:
procedure ScanFolder(const Path: String);
var
sPath: string;
rec : TSearchRec;
begin
sPath := IncludeTrailingPathDelimiter(Path);
if FindFirst(sPath + '*.*', faAnyFile, rec) = 0 then
begin
repeat
// TSearchRec.Attr contain basic attributes (directory, hidden,
// system, etc). TSearchRec only supports a subset of all possible
// info. TSearchRec.FindData contains everything that the OS
// reported about the item during the search, if you need to
// access more detailed information...
if (rec.Attr and faDirectory) <> 0 then
begin
// item is a directory
if (rec.Name <> '.') and (rec.Name <> '..') then
ScanFolder(sPath + sr.Name);
end
else
begin
// item is a file
end;
until FindNext(rec) <> 0;
FindClose(rec);
end;
end;
ScanFolder('c:\test');
Run Code Online (Sandbox Code Playgroud)