Checking if a directory is empty using File

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.

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

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

Why not simply use that expression?

Dir["*"].empty?

Al Evans schrieb:

Dir["*"].empty?