Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: How to know how much used space of a path?

by hanspr (Sexton)
on Nov 20, 2021 at 05:20 UTC ( [id://11138969]=note: print w/replies, xml ) Need Help??


in reply to How to know how much used space of a path?

You could use a recursive sub to get the size of each file in the path and accumulate de bytes and then return the total bytes accumulated.

That gives you the size of the directory, and then you need a reference to the maximum allowed size to be able to get a percentage.


#!/usr/bin/perl our $used = get_used_space("/path/to/dir",10000000); print "Used space -> $used %\n"; sub get_used_space { my $dir = shift; my $max = shift; if ($max <= 0) { return 0; } my $current_size = get_space($dir); return int(($current_size / $max) * 10000)/100; } sub get_space { my $dir = shift; my $d; my $bytes = 0; opendir($d,$dir); while (my $f = readdir($d)) { if ($f eq '.' || $f eq '..') { next; } my $file = "$dir/$f"; if (-d $file) { $bytes += get_space("$file"); } if (-f $file) { my $size = -s "$file"; $bytes += $size; } } return $bytes; }

Replies are listed 'Best First'.
Re^2: How to know how much used space of a path?
by Fletch (Bishop) on Nov 20, 2021 at 05:48 UTC

    Nitpicks:

    • You're reimplementing the standard File::Find module which does this (correctly) for you (to say nothing of other similar modules available from CPAN such as File::Find::Rule, Path::Tiny, Path::Iterator::Rule, . . .)
    • On OSen and/or filesystems which allow sparse files there's usually a way to ask du to account for that fact and get the actual space used by the file; summing the sizes returned by stat(2) (via caling stat or the -s operator) won't.
    • You don't check the return value from opendir; ALWAYS CHECK THE RETURN VALUE FROM SYSTEM CALLS.
    • You're needlessly stringifying in a couple places, e.g. -s "$file"; not necessarily a problem in this particular case but it's a bad habit to develop. Somewhere down the road you're going to have an object instance for a class which has overloaded stringification that you DIDN'T mean to turn into just a string and then you're going to have to debug why you're getting an error about not being able to locate method foo via package bar from somewhere deep down in your code.

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11138969]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (8)
As of 2024-04-25 11:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found