代码之家  ›  专栏  ›  技术社区  ›  Omair Iqbal

findfirst,findnext列出文件,但不列出目录…?

  •  0
  • Omair Iqbal  · 技术社区  · 17 年前

    以下代码列出了文件,但没有列出目录

    var 
    rec : tsearchrec;
    begin
    findfirst('c:\test\*',faanyfile-fadirectory,rec);
            showmessage(rec.Name);
    if findnext(rec) <> 0 then close else
    showmessage (rec.Name);
    end;
    
    5 回复  |  直到 14 年前
        1
  •  18
  •   Francesca    17 年前
    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;
    
        2
  •  5
  •   Remy Lebeau    14 年前

    Read the documentation 关于过滤器的实际工作方式:

    attr参数指定要包含的特殊文件 此外 所有普通文件 .

    换言之, FindFirst() 始终返回普通文件,而不考虑您指定的任何筛选条件。这个 Attr 参数仅包括 其他 基本筛选器中的属性类型。你需要测试 TSearchRec.Attr 字段确定报告的条目实际上是文件还是目录,例如:

    if (rec.Attr and faDirectory) <> 0 then
      // item is a directory
    else
      // item is a file
    

    如果实现递归搜索循环,请确保忽略“.”和“..”目录,否则循环将不确定地重复:

    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');
    
        3
  •  4
  •   devio    17 年前

    通过在flags参数中声明“-fadirectory”,可以显式排除目录。

        4
  •  2
  •   utku_karatas    17 年前

    关于findfirst(“c:\test \*”, 传真文件 ,rec);//不是faanyfile fadirectory

        5
  •  -2
  •   Joe    17 年前

    如果您想要所有的文件和目录,只需将fadirectory传递给findfirst。它已经把文件还给你了。