Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: quickest way to find number of files in a directory?

by trizen (Hermit)
on Dec 11, 2011 at 02:50 UTC ( [id://942896]=note: print w/replies, xml ) Need Help??


in reply to quickest way to find number of files in a directory?

Here is a pretty fast script that finds the number of files and directories in a given path.
#!/usr/bin/perl use strict; my $f; # number of files my $d; # number of dirs sub count_files { my ($ref) = @_; foreach my $dir (@$ref) { $dir = readlink $dir and chop $dir if -l $dir; # read link next unless opendir(my $dir_h, $dir); # open dir o +r next my @dirs; while (defined(my $file = readdir $dir_h)) { if ($file eq '.' or $file eq '..') { next; } if (-d "$dir/$file") { ++$d; # counting d +irs push @dirs, "$dir/$file"; } elsif(-f _){ ++$f; # counting f +iles } } closedir $dir_h; count_files(\@dirs); } [$f, $d]; } foreach my $arg (@ARGV) { my @dir = -d $arg ? $arg : next; ($f, $d) = (0, 0); print "$arg\nFiles\t: $$_[0]\nDirs\t: $$_[1]\n" for count_files(\@ +dir); }

Usage:
$ time perl test.pl /tmp/ /usr/bin/ /media/ /tmp/ Files : 844 Dirs : 15 /usr/bin/ Files : 1564 Dirs : 3 /media/ Files : 10031 Dirs : 689 real 0m0.111s user 0m0.030s sys 0m0.070s

Replies are listed 'Best First'.
Re^2: quickest way to find number of files in a directory?
by tqviet (Acolyte) on Apr 21, 2018 at 06:03 UTC
    Dear trizen, Thank you very much. I have checked around and so far I can conclude that Your Perl script works correctly and efficiently. Especially, it runs rapidly.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://942896]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (3)
As of 2024-04-26 04:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found