Findfirst,findnext列出文件但不是目录......?

Oma*_*bal 0 delphi

以下代码列出文件但不列出目录

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

  1. 您不需要排除目录,不幸的是您使用(-faDirectory)
  2. 完成后你必须调用FindClose.
  3. 如果要查找目录中的所有内容,则需要循环
var
 rec : tsearchrec;
begin
  if FindFirst('c:\*', faAnyFile, rec) = 0 then
  begin
    repeat
      ShowMessage(rec.Name);
    until FindNext(rec) <> 0;
    FindClose(rec);
  end;
end;
Run Code Online (Sandbox Code Playgroud)

  • 奥马尔,"." 和".."是目录条目,就像任何其他目录条目一样.您只需确保您的代码可以处理它们.而且,你可能已经意识到`FirstFirst`不是很擅长*排除*结果.通常的做法是使用`FindFirst`和`FindNext`来枚举*all*文件和目录,然后在你自己的代码中检查你需要的标准,并跳过你不想要的标准. (3认同)
  • @Omair:"." 是当前目录的别名,".."是父目录.如果在命令提示符下键入"cd ..",则将从当前目录移动到其父目录. (2认同)

Rem*_*eau 5

阅读有关过滤器实际工作原理的文档:

除了所有普通文件外, 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)