Forum: Ruby on Rails Checking if a directory is empty using File

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Sam D. (Guest)
on 2006-06-06 11:55
(Received via mailing list)
Hi,

I have one minor issue.  I'm trying to check whether a directory is
empty
given some path to the directory.

My code does the following:

if(File.directory?(dirpath))   # dirpath = public/images/1
  if(File.zero?(dirpath))
    FileUtils.rm_rf(dirpath)
  end
end

The problem is, while testing this, if I put a file in the directory and
run
the above code, it still ends up deleting the entire directory which
doesn't
make sense since File.zero? should not return true.  I even tried using
File.size?(dirpath) but that doesn't work either.

Any help would be appreciated.

Thanks,

Saureen.
Chris H. (Guest)
on 2006-06-06 16:14
(Received via mailing list)
try something like this instead (in irb)

if File.directory?(dirname)
  begin
    # try to delete the directory
    # Dir.delete raises a SystemCallError if the named directory is not
empty
    Dir.delete(dirpath)
  rescue SystemCallError => e
    # handle the exception here (ie, directory was not deleted because
it
was not empty)
    puts e
  end
else
  puts "#{dirname} is not a directory"
end
Al E. (Guest)
on 2006-06-06 18:57
Sam D. wrote:
> Hi,
>
> I have one minor issue.  I'm trying to check whether a directory is
> empty
> given some path to the directory.
>
> My code does the following:
>
> if(File.directory?(dirpath))   # dirpath = public/images/1
>   if(File.zero?(dirpath))
>     FileUtils.rm_rf(dirpath)
>   end
> end
>
> The problem is, while testing this, if I put a file in the directory and
> run
> the above code, it still ends up deleting the entire directory which
> doesn't
> make sense since File.zero? should not return true.  I even tried using
> File.size?(dirpath) but that doesn't work either.
>
> Any help would be appreciated.

File.zero? will just tell you if you have a zero-length file, which a
directory is not.

You could say

if Dir.entries(dirpath).size < 2 # two entries for "." and ".."

What I'd do, though is:

require 'pathname'
if Pathname.new(dirpath).children.size == 0

I've already spent enough time struggling with File and Dir; Pathname
makes things like this a lot easier:-)

--Al Evans
Pete (Guest)
on 2006-06-07 13:31
(Received via mailing list)
Why not simply use that expression?

 Dir["*"].empty?




Al Evans schrieb:
Peter E. (Guest)
on 2006-06-07 13:53
(Received via mailing list)
Dir["*"].empty?
This topic is locked and can not be replied to.