# Last update: 2009/08/15 # # Calculation of sum of file sizes of all subdirs # # (p) Jerry Nagasaki # # # INPUT: actual sub directory file size amount # ARGUMENTS: -a output all found files and size # -A output all found files and size and add bar between different directories # OUTPUT: size amount and optional sub directories, files and filesizes # # Note: Does not include amount of directory administration sizes of FAT16, FAT32 or NTFS # use Cwd; # for "cwd" # get argument, if existing $list = 0; # list all files $bar = 0; foreach (@ARGV) { $list = 1 if ($_ eq "-a"); $bar = 1 if ($_ eq "-A"); } # global directory list @filepath; # root directory or current (as here) $rootdir = "."; # call to recursive self calling sub routine getdir($rootdir); unshift(@filepath, $rootdir); # add root directory # not perfect ordering for sub directories, but better than nothing ;-) @filepath = sort(Nocase @filepath); $filesizes = 0; # ... and just for intialization ... ;-) print cwd . "\n" if (($list + $bar) > 0); # print root directory (uses Cwd) # show results foreach (@filepath) { $thispath = $_; opendir(DIR, "$_"); my @files = readdir(DIR); closedir(DIR); @files = sort(Nocase @files); print "-------------------------\n" if ($bar == 1); foreach (@files) { # exclude ".", ".." and directories if (($_ ne "\.") && ($_ ne "\.\.") && !(-d "$thispath\\$_")) { $size = -s "$thispath\\$_"; print "$thispath\\$_ - $size\n" if (($list + $bar) > 0); $filesizes += $size; } } } print "\nTotal size: $filesizes Bytes\n"; $filesizes_temp = int ($filesizes / 10.24) / 100; print " $filesizes_temp KBytes\n"; $filesizes_temp = int ($filesizes / 10485.76) / 100; print " $filesizes_temp MBytes\n"; #-------------------------- # get directory (recursive called subroutine) # all variables have to be declared with "my" to give them their # own area of validity in the actual recursion level sub getdir { my $dir = shift; opendir(DIR, "$dir"); # UPDATE: Speed-up (Files w/o "."): my @files = grep {!/\./} readdir(DIR); my @files = readdir(DIR); closedir(DIR); foreach (@files) { my $newdir = "$dir\\$_"; # create absolute path # check if directory and not "." or ".." # UPDATE: Speed-up (Files w/o "."): if (-d $newdir) if ((-d $newdir) && ($_ ne "\.") && ($_ ne "\.\.")) { push (@filepath, $newdir); # add new directory getdir($newdir); # recursive call } } } # sorting w/o upper- or lowercase sub Nocase { # Don't touch $a or $b, because it would change caller list! $aa = lc($a); $bb = lc($b); if($aa lt $bb) { return -1; } elsif($aa eq $bb) { return 0; } else { return 1; } }