是一个递归查找文件的程序看看FindFirst函数的用法你就清楚了

解决方案 »

  1.   


    function GetFileCount(srcPath, srcFileName: string): Integer; //函数名,参数srcPath:要搜索的路径,srcFileName:要搜索的文件名
    var //声明变量
      FileRec: TSearchrec; //用于保存搜索结果的记录
      currPath: string; //当前路径,临时变量
    begin
      if srcPath[Length(srcPath)] <> '\' then srcPath := srcPath + '\'; //如果路径不是以\结尾,则加上\
      currPath := srcPath + '*.*'; //搜索的文件通配符,*.*表示查找所有文件
      Result := 0; //结果数初始化为0
      if FindFirst(currPath, faAnyFile, FileRec) = 0 then //开始查找
        repeat //重复循环
          if ((FileRec.Attr and faDirectory) <> 0) and //如果找到的文件是一个目录
            (FileRec.Name <> '.') and //当前目录
            (FileRec.Name <> '..') then //上级目录
          begin
            Result := Result + GetFileCount(srcPath + FileRec.Name, srcFileName); //继续在子目录里面递归查找
          end else
          if AnsiCompareText(srcFileName, FileRec.Name) = 0 then //如果找到的文件不是目录,则对比文件名是否是要找的文件名,如果是,结果数+1
            Result := Result + 1;
        until FindNext(FileRec) <> 0; //知道没有更多文件了,跳出循环
    end;
      

  2.   

    function GetFileCount(srcPath, srcFileName: string): Integer;
           // GetFileCount :函数名
           // srcPath      :string值参数(要搜索的目录名)
           // srcFileName  :string值参数(搜索的文件名)
    var 
      FileRec: TSearchrec; // 声明为TSearchrec类型局部变量,保存搜索结果的记录
      currPath: string;    // 声明为string类型局部变量,保存当前路径
    begin
      if srcPath[Length(srcPath)] <> '\' then srcPath := srcPath + '\'; 
          // 条件语句,检查srcPath结尾字符不是\,加上一个\字符
      currPath := srcPath + '*.*'; // 指定搜索的文件通配符,*.*表示所有文件
      Result := 0;         // 函数返回为0(初始值,后面不追加,就返回此值)
      if FindFirst(currPath, faAnyFile, FileRec) = 0 then 
         // 查找从第一个文件开始 faAnyFile:指定任何文件
        repeat             // repeat循环,先执行,尾部判断是否循环
          if ((FileRec.Attr and faDirectory) <> 0) and // 搜索的文件是目录
            (FileRec.Name <> '.') and                  // 搜索的文件是(.代表当前目录)
            (FileRec.Name <> '..') then                // 搜索的文件上级目录(..代表当前目录)
          begin
            Result := Result + GetFileCount(srcPath + FileRec.Name, srcFileName);
               // 确定是目录,就在进入子目录继续搜索(进入递归,调用自身)
          end else
            if AnsiCompareText(srcFileName, FileRec.Name) = 0 then 
              Result := Result + 1;
              // 如果是文件,又是相同文件名,记录+1
        until FindNext(FileRec) <> 0;         
              // repeat循环的尾部,判断还有文件继续循环,否则跳出循环
    end;上述解释,应该满意了吧。