Calculate size of all files in a Directory

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • vasu1308
    New Member
    • Feb 2007
    • 31

    Calculate size of all files in a Directory

    Hi ,
    Can anyone help me in finding the number of files and their size in Directory.
  • miller
    Recognized Expert Top Contributor
    • Oct 2006
    • 1086

    #2
    You simply need to read in the contents of the directory and add up the size of each of the files. Pertinent documentation can be found here:

    http://perldoc.perl.org/functions/readdir.html - read in the files
    http://perldoc.perl.org/functions/-X.html - obtain the size of the file
    http://perldoc.perl.org/functions/stat.html - alternate method for file size.

    Comment

    • KevinADC
      Recognized Expert Specialist
      • Jan 2007
      • 4092

      #3
      I find stuff like this easier to do with a shell command but if it needs to be portable then use the File::Find module or write your own function to recurse directories and add up the file sizes. You can use the -s file test operator to get the size.

      Comment

      • docsnyder
        New Member
        • Dec 2006
        • 88

        #4
        Originally posted by vasu1308
        Hi ,
        Can anyone help me in finding the number of files and their size in Directory.
        You do not even need a module:
        Code:
        sub dirSize {
          my($dir)  = @_;
          my($size) = 0;
          my($fd);
        
          opendir($fd, $dir) or die "$!";
        
          for my $item ( readdir($fd) ) {
            next if ( $item =~ /^\.\.?$/ );
        
            my($path) = "$dir/$item";
        
            $size += ((-d $path) ? dirSize($path) : (-f $path ? (stat($path))[7] : 0));
          }
        
          closedir($fd);
        
          return($size);
        }
        Greetz, Doc
        Last edited by miller; Feb 21 '07, 08:27 AM. Reason: fixed use strict.

        Comment

        Working...