Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

How to tell if a Directory is Empty

by ishootperls (Novice)
on Oct 28, 2011 at 19:04 UTC ( #934482=CUFP: print w/ replies, xml ) Need Help??

I needed to find a quick way to find out if a directory was empty or not. After hours (30 minutes) of google searching, I didnt find anything worth using. So I wrote my own code, which is what I should have done if I wasnt trying to find the easy way out. Enjoy! Feel free to chime in.

$i=0; opendir(DIR, "$someDir") or die "Cant open $someDir: $!\n"; @files = readdir(DIR); foreach $file(@files) { unless ($file =~ /^[.][.]?\z/) { $i++; } } if ($i != 0) { print "There is Stuff in here!"; } else { print "This Dir is Empty!"; } closedir(DIR);
"I think it's a new feature. Don't tell anyone it was an accident." :-) - L. Wall

Comment on How to tell if a Directory is Empty
Download Code
Re: How to tell if a Directory is Empty
by choroba (Abbot) on Oct 28, 2011 at 20:49 UTC
    You can also use stat. Not sure about other platforms, but on my linux box, (stat "dirname")[7] == 48 indicates an empty dir.
      on my linux box, (stat "dirname")[7] == 48 indicates an empty dir

      Very unreliable. That depends on the filesystem, on the filesystem options, and on the history of the directory. On my linux box with an old but large ext3 filesystem, most directories report a size of 4096, even freshly created ones. Only directorys that once had several hundred files grow larger, and they keep their larger size even when all files are removed.

      Alexander

      --
      Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)
Re: How to tell if a Directory is Empty
by JavaFan (Canon) on Oct 28, 2011 at 23:21 UTC
    Assuming one has write permission to its parent directory, do {print "This Dir is Empty!"; mkdir $someDir"} if rmdir $someDir; is a quick way to find this out as well.
Re: How to tell if a Directory is Empty
by ww (Bishop) on Oct 28, 2011 at 23:48 UTC
    Slight increase of Perlishness possible at line 5: No need for char classes; simply escape the dot and use the "+" quantifier (1 or more instances). IOW, make the regex unless ($file =~ /^\.+\z/) {

    Further slight increase in Perlishness: Don't reinvent the wheel. Check out some of the File:... modules for the means to seek out UNsuspected no-file subdirs.

    Nonetheless, ++ for developing your own approach which satisfies the specific spec you provide.
      IOW, make the regex unless ($file =~ /^\.+\z/)
      Why would you change something that's correct, into something that isn't? Be aware that ... is a legal file name, and has not special meaning. And so is ..........

      I see nothing wrong the OPs regexp -- except that using a /[.]/ is a performance hit over /\./ in pre-5.10 versions of Perl. But I rather be slow and correct, than fast and incorrect.

Re: How to tell if a Directory is Empty
by aaron_baugher (Deacon) on Oct 29, 2011 at 02:17 UTC

    You can grep the list of files for anything other than '.' and '..', and since any results from grep will equal true:

    opendir my $dir, $dirname or die $!; if( grep ! /^\.\.?$/, readdir $dir ){ print 'stuff in here'; }

      You are using the $ anchor instead of the \z anchor which means that the directory will be considered empty if there is a valid file named ".\n" or "..\n".

Re: How to tell if a Directory is Empty
by zentara (Archbishop) on Oct 29, 2011 at 10:47 UTC
    Here is some similar code that various monks posted awhile back. There are a few varieties of an isEmpty() sub
    #!/usr/bin/perl # Returns: # 1 - empty # 0 - not empty # -1 - doesn't exist # Definition of "empty" -- no files/folders/links except . and .. sub isEmpty{ my ($dir) = @_; my $file; if (opendir my $dfh, $dir){ while (defined($file = readdir $dfh)){ next if $file eq '.' or $file eq '..'; closedir $dhf; return 0; } closedir $dfh; return 1; }else{ return -1; } } ####### sub isEmpty1 { opendir(DIR,shift) or die $!; my @files = grep { !m/\A\.{1,2}\Z/} readdir(DIR); closedir(DIR); @files ? 0 : 1; } print isEmpty1('./dir') ? "empty\n" : "not empty\n"; ################# sub isEmpty2 { return undef unless -d $_[0]; opendir my $dh, $_[0] or die $!; my $count = () = readdir $dh; # gets count thru () return $count - 2; #maybe not the best way of removing . and . +. }

    I'm not really a human, but I play one on earth.
    Old Perl Programmer Haiku ................... flash japh
      return $count - 2; #maybe not the best way of removing . and . +.
      Perhaps use grep for that?
      sub isEmpty3 { return undef unless -d $_[0]; opendir my $dh, $_[0] or die $!; my $count = grep { ! /^\.{1,2}/ } readdir $dh; # strips out . and +.. return $count; }


Re: How to tell if a Directory is Empty
by mhi (Friar) on Nov 23, 2011 at 06:13 UTC
    To save time on large directories, you will probably want to add a last; after your $i++;. That way, the loop will never run more than three iterations.
Re: How to tell if a Directory is Empty
by TJPride (Pilgrim) on Nov 26, 2011 at 18:34 UTC
    use strict; use warnings; my $error; if (!dirEmpty($ARGV[0], $error)) { print $error ? "$error\n" : "Directory contains files.\n"; } else { print "Directory is empty.\n"; } sub dirEmpty { if (!-e $_[0]) { $_[1] = 'Directory does not exist.'; return; } if (!-d $_[0]) { $_[1] = 'Path does not reference a directory.'; return; } if (!opendir(DIR, $_[0])) { $_[1] = 'Could not open directory.'; return; } while ($_ = readdir(DIR)) { next if m/^\.\.?$/; return; } return 1; }

      I was trying to be clever, so I discovered IO::Dir and seekdir

      I wrote this code, and then had a WTF moment

      sub dirEmpty { my $d = IO::Dir->new( @_ ); return defined( $d && $d->seek( 2 ) && scalar $d->read ); }

      seekdir is broken on my win32 machine :)

Re: How to tell if a Directory is Empty
by tobyink (Abbot) on Feb 27, 2012 at 11:15 UTC
    use 5.010; use Path::Class qw(dir); my $dir = dir("/etc/httpd"); my $is_empty = $dir->stat && !$dir->children;

    The $dir->stat call is needed because $dir->children throws on non-existent directories.

Re: How to tell if a Directory is Empty
by tos (Deacon) on Apr 14, 2014 at 11:39 UTC
    # ls 1 2 3 4 5 # ls -al * 1: total 0 drwxr-xr-x 2 root root 6 Apr 14 13:22 . drwxr-xr-x 7 root root 46 Apr 14 13:22 .. 2: total 4 drwxr-xr-x 2 root root 16 Apr 14 13:22 . drwxr-xr-x 7 root root 46 Apr 14 13:22 .. -rw-r--r-- 1 root root 5 Apr 14 13:22 two 3: total 0 drwxr-xr-x 2 root root 6 Apr 14 13:22 . drwxr-xr-x 7 root root 46 Apr 14 13:22 .. 4: total 4 drwxr-xr-x 2 root root 17 Apr 14 13:22 . drwxr-xr-x 7 root root 46 Apr 14 13:22 .. -rw-r--r-- 1 root root 5 Apr 14 13:23 four 5: total 0 drwxr-xr-x 2 root root 6 Apr 14 13:22 . drwxr-xr-x 7 root root 46 Apr 14 13:22 .. # perl -we 'use Data::Dumper;@d=grep {<$_/*>} (<*>);print Dumper \@d' $VAR1 = [ '2', '4' ]; # perl -we 'use Data::Dumper;@d=grep {!<$_/*>} (<*>);print Dumper \@d' $VAR1 = [ '1', '3', '5' ]; #

    Is simplicity best or simply the easiest Martin L. Gore

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: CUFP [id://934482]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (5)
As of 2014-08-30 01:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (291 votes), past polls