查找srcPath目录下的包含有srcFileName文件的文件个数,并且包含子目录

解决方案 »

  1.   

    unction 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;