Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I am writing a file manager script for my website, and ran into difficulty. I was wondering is there any way to get the size of a directory??? not a file... Please help I am lost and need desperate guideance...

Replies are listed 'Best First'.
Re: looking for simple solution
by jjhorner (Hermit) on Jun 15, 2000 at 20:53 UTC

    Try this:

    my $dir = "//home//schmoe//somedir"; my $dirsize = -s $dir || die "can't stat dir $dir: $!";

    It should work. Any other ideas?

    Update:

    for those of us with real operating systems:

    `du -ks`
    works just fine.

    Update #2:

    I found this in the Perl Cookbook, and made it a standalone bit of code:

    #!/usr/bin/perl -w use strict; use File::Find; @ARGV = ('.') unless @ARGV; my $sum = 0; find sub { $sum += -s }, @ARGV; print "@ARGV contains $sum bytes\n";

    This should be the ticket.

    J. J. Horner
    Linux, Perl, Apache, Stronghold, Unix
    jhorner@knoxlug.org http://www.knoxlug.org/
    
      JJ, out of curiosity, why did you do:
      my $dir = "//home//schmoe//somedir";

      (i.e. the double slashes?) The only place where I've found this appropriate is when using paths in the DOS/Win32 format, as obviously if you did c:\noddy if a double-quoted string, Perl looks for a dir named 'c: linebreak oddy'.

      Is there something I don't know about here? BTW Win32 users - you can use the UNIX-style slashes when telling Perl to open files etc! I far prefer / to \!

Re: looking for simple solution
by plaid (Chaplain) on Jun 15, 2000 at 20:58 UTC
    I'm not quite sure what you mean by the size of a directory. If what you want is the actual byte size of the directory itself, you can just do
    $size = (-s $directory);
    If what you mean by size is the size of everything within it, you'll probably have to code something up by hand, preferably using File::Find to handle your recursion. I did a quick look on CPAN, but was unable to find any modules to handle disk usage.

    If you do want the size of everything in the directory, and you're on unix, you can mess around with playing with the output of the system command 'du', but I don't recommend this for any script that will have a long life.

A reply falls below the community's threshold of quality. You may see it by logging in.