in reply to Getting the size of files and stuff

Something like this ...

sub dir_size { my $dir = shift; local *DIR; my $size = 0; my $file; opendir(DIR, $dir) or die "Failed to open $dir: $!\n"; while ($file = readdir(DIR)) { # Skip . and .. if ($file !~ /^\.\.?$/) { if (-d "$dir/$file") { $size += dir_size("$dir/$file"); } else { $size += -s "$dir/$file"; } } } closedir(DIR); return $size; } my $size = dir_size("/foo/bar");

Replies are listed 'Best First'.
Re^2: Getting the size of files and stuff
by Aristotle (Chancellor) on Jul 07, 2002 at 12:44 UTC

    $ cd /foo/bar ; ln -s . snaretrap

    Now watch that code run forever.

    Check for symlinks before you recurse. Of course, if several files are hardlinked to each other below /foo/bar/, they will be counted multiple times, which may or may not be desired - likely not. stat files and check if you've seen that combination of device and inode number before. Etc etc etc..

    It's only an innocent looking problem.

    Makeshifts last the longest.

Re: Re: Getting the size of files and stuff
by fruiture (Curate) on Jul 07, 2002 at 10:21 UTC
    You should get a warning that readdir might return "false" values, e.g. a file named "0".

    while(defined(my $file = readir DIR)){

    Anyway it's better to use File::Find.
A reply falls below the community's threshold of quality. You may see it by logging in.