Forum Moderators: coopster & phranque

Message Too Old, No Replies

Getting the size of a directory above the current one.

It works for directories below, but not above...

         

adni18

12:40 am on Apr 24, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi everyone. I have a script that determines how large a directory is. It seems to work fine for directories above the current directory, such as Projects or Main, but it fails to find the size of directories below or level to the current directory, like ../Raisin or ..

Why, and how can it be fixed?

print &DirSize( "Projects" );

sub DirSize {
use POSIX;
my ( $path ) = @_;
my $dirSize;
my ( @dirContents, $name, $fileName );

if ( -f $path ) { die "Not a directory!\n"; }

opendir ( DIR, $path ) or die "Can't open directory $path!\n";
@dirContents = grep (/[^\.]/, readdir(DIR));# remove . i ..
foreach $name (@dirContents) {
$fileName = $path."\\".$name;

# if it is file, add size, otherwise recursively call DirSize
if (-f $fileName) {
${$dirSize} = ${$dirSize} + (stat($fileName))[7];
}
else {DirSize($fileName, \${$dirSize}); }
}
return (floor(($dirSize/1048576)*100)/100) . " MB";
}

wruppert

3:40 am on Apr 24, 2005 (gmt 0)

10+ Year Member



This seems to work for me. ActiveState, WinXP.
I fixed the subroutine to actually use the size accumulator. I got rid of the unneeded ${}'s. I'm not exactly sure what causes your problem - make sure to put two \\ in the file name. Use "use warnings;", it complained about something related to those extra {}'s.


#!/usr/bin/perl

use strict;
use warnings;

print &DirSize( "..\\cgi" );

sub DirSize {
use POSIX;
my $path = shift;
my $dirSize = shift ¦¦ 0;

my ( @dirContents, $name, $fileName );

if ( -f $path ) { die "Not a directory!\n"; }

opendir ( DIR, $path ) or die "Can't open directory $path!\n";
@dirContents = grep (/[^\.]/, readdir(DIR));# remove . i ..
foreach $name (@dirContents) {
$fileName = $path."\\".$name;

# if it is file, add size, otherwise recursively call DirSize
if (-f $fileName) {
$dirSize += (stat($fileName))[7];
}
else {
DirSize($fileName, $dirSize);
}
}
return (floor(($dirSize/1048576)*100)/100) . " MB";
}

wruppert

3:42 am on Apr 24, 2005 (gmt 0)

10+ Year Member



And those broken bars are supposed to be solid bars. I guess the forum software changes them.