Matthew Hipkin

Recursively count files with Delphi or FreePascal

Download: https://github.com/hippy2094/countr

procedure DoCount(mask: String; inDir: String; var filecount: Integer);
var
  s: TSearchRec;  
begin
  writeln('Searching for ',mask,' in ',inDir);
  if FindFirst(IncludeTrailingPathDelimiter(inDir) + '*',faAnyFile, s) = 0 then
  begin
    repeat
      if (s.Attr and faDirectory) <> faDirectory then
      begin
        if (Lowercase(ExtractFileExt(s.Name)) = Lowercase(ExtractFileExt(mask))) or (mask = '*.*') then
        begin
          inc(filecount);  
        end;    
      end;
      if (s.Name <> '.') and (s.Name <> '..') and ((s.Attr and faDirectory) = faDirectory) then
      begin
        DoCount(mask, IncludeTrailingPathDelimiter(inDir) + s.Name, filecount);
      end;
    until FindNext(s) <> 0;
  end;
  FindClose(s);
end;

Usage is simple: search for mask in inDir, storing the count in filecount.

blog comments powered by Disqus