Empty directory
You are encouraged to solve this task according to the task description, using any language you may know.
Starting with a path to some directory, determine whether the directory is empty.
An empty directory contains no files nor subdirectories.
With Unix or Windows systems, every directory contains an entry for “.
” and almost every directory contains “..
” (except for a root directory); an empty directory contains no other entries.
Ada
<lang Ada>with Ada.Text_IO; use Ada.Text_IO; with Ada.Directories; procedure EmptyDir is
function Empty (path : String) return String is use Ada.Directories; result : String := "Is empty."; procedure check (ent : Directory_Entry_Type) is begin if Simple_Name (ent) /= "." and Simple_Name (ent) /= ".." then Empty.result := "Not empty"; end if; end check; begin if not Exists (path) then return "Does not exist."; elsif Kind (path) /= Directory then return "Not a Directory."; end if; Search (path, "", Process => check'Access); return result; end Empty;
begin
Put_Line (Empty (".")); Put_Line (Empty ("./empty")); Put_Line (Empty ("./emptydir.adb")); Put_Line (Empty ("./foobar"));
end EmptyDir;</lang>
- Output:
Not empty Is empty. Not a Directory. Does not exist.
AutoHotkey
<lang autohotkey>MsgBox % isDir_empty(A_ScriptDir)?"true":"false"
isDir_empty(p) { Loop, %p%\* , 1 return 0 return 1 }</lang>
- Output:
false
BBC BASIC
<lang bbcbasic> IF FNisdirectoryempty("C:\") PRINT "C:\ is empty" ELSE PRINT "C:\ is not empty"
IF FNisdirectoryempty("C:\temp") PRINT "C:\temp is empty" ELSE PRINT "C:\temp is not empty" END DEF FNisdirectoryempty(dir$) LOCAL dir%, sh%, res% DIM dir% LOCAL 317 IF RIGHT$(dir$)<>"\" dir$ += "\" SYS "FindFirstFile", dir$+"*", dir% TO sh% IF sh% = -1 ERROR 100, "Directory doesn't exist" res% = 1 REPEAT IF $$(dir%+44)<>"." IF $$(dir%+44)<>".." EXIT REPEAT SYS "FindNextFile", sh%, dir% TO res% UNTIL res% == 0 SYS "FindClose", sh% = (res% == 0)</lang>
C
<lang c>#include <stdio.h>
- include <dirent.h>
- include <string.h>
int dir_empty(const char *path) { struct dirent *ent; int ret = 1;
DIR *d = opendir(path); if (!d) { fprintf(stderr, "%s: ", path); perror(""); return -1; }
while ((ent = readdir(d))) { if (!strcmp(ent->d_name, ".") || !(strcmp(ent->d_name, ".."))) continue; ret = 0; break; }
closedir(d); return ret; }
int main(int c, char **v) { int ret = 0, i; if (c < 2) return -1;
for (i = 1; i < c; i++) { ret = dir_empty(v[i]); if (ret >= 0) printf("%s: %sempty\n", v[i], ret ? "" : "not "); }
return 0;
}</lang>Running it:
% mkdir stuff; ./a.out /usr/ ./stuff /etc/passwd /usr/: not empty ./stuff: empty /etc/passwd: Not a directory
C++
<lang cpp>
- include <iostream>
- include <boost/filesystem.hpp>
using namespace boost::filesystem;
int main(int argc, char *argv[]) {
for (int i = 1; i < argc; ++i) { path p(argv[i]);
if (exists(p) && is_directory(p)) std::cout << "'" << argv[i] << "' is" << (!is_empty(p) ? " not" : "") << " empty\n"; else std::cout << "dir '" << argv[i] << "' could not be found\n"; }
} </lang>
C#
<lang csharp>using System; using System.IO;
class Program {
static void Main( string[] args ) { foreach ( string dir in args ) { Console.WriteLine( "'{0}' {1} empty", dir, IsDirectoryEmpty( dir ) ? "is" : "is not" ); } }
private static bool IsDirectoryEmpty( string dir ) { return ( Directory.GetFiles( dir ).Length == 0 && Directory.GetDirectories( dir ).Length == 0 ); }
} </lang>
Running it:
Assume c:\temp exists and is not empty, c:\temp\empty exists and is empty c:\>IsEmptyDir c:\temp c:\temp\empty 'c:\temp' is not empty 'c:\temp\empty' is empty
Clojure
<lang clojure>(require '[clojure.java.io :as io]) (defn empty-dir? [path]
(let [file (io/file path)] (assert (.exists file)) (assert (.isDirectory file)) (-> file .list empty?))) ; .list ignores "." and ".."</lang>
CoffeeScript
<lang coffeescript> fs = require 'fs'
is_empty_dir = (dir) ->
throw Error "#{dir} is not a dir" unless fs.statSync(dir).isDirectory() # readdirSync does not return . or .. fns = fs.readdirSync dir fns.length == 0
</lang>
Common Lisp
Will also return T
if path
doesn't exist.
<lang lisp>
(defun empty-directory-p (path)
(and (null (directory (concatenate 'string path "/*"))) (null (directory (concatenate 'string path "/*/")))))
</lang>
D
<lang d>import std.stdio, std.file;
void main() {
auto dir = "somedir"; writeln(dir ~ " is empty: ", dirEmpty(dir));
}
bool dirEmpty(string dirname) {
if (!exists(dirname) || !isDir(dirname)) throw new Exception("dir not found: " ~ dirname); return dirEntries(dirname, SpanMode.shallow).empty;
}</lang>
somedir is empty: false
Erlang
From the Erlang shell, or in a program, match {ok, []}. It this works the directory is empty.
- Output:
3> {ok, []} = file:list_dir_all("/usr"). ** exception error: no match of right hand side value {ok,["X11R6","X11","standalone","share","sbin","local", "libexec","lib","bin"]} 4> {ok, []} = file:list_dir_all("/asd"). ** exception error: no match of right hand side value {error,enoent} 5> {ok, []} = file:list_dir_all("./empty"). {ok,[]}
F#
<lang fsharp>open System.IO let isEmptyDirectory x = (Directory.GetFiles x).Length = 0 && (Directory.GetDirectories x).Length = 0</lang>
Go
<lang go>package main
import ( "fmt" "io/ioutil" "log" )
func main() { empty, err := IsEmptyDir("/tmp") if err != nil { log.Fatalln(err) } if empty { fmt.Printf("/tmp is empty\n") } else { fmt.Printf("/tmp is not empty\n") } }
func IsEmptyDir(name string) (bool, error) { entries, err := ioutil.ReadDir(name) if err != nil { return false, err } return len(entries) == 0, nil } </lang>
Groovy
Solution: <lang groovy>def isDirEmpty = { dirName ->
def dir = new File(dirName) dir.exists() && dir.directory && (dir.list() as List).empty
}</lang>
Test: <lang groovy>def currentDir = new File('.') def random = new Random() def subDirName = "dir${random.nextInt(100000)}" def subDir = new File(subDirName) subDir.mkdir() subDir.deleteOnExit()
assert ! isDirEmpty('.') assert isDirEmpty(subDirName)</lang>
Haskell
<lang haskell>import System.Directory (getDirectoryContents) import System.Environment (getArgs)
isEmpty x = getDirectoryContents x >>= return . f . (== [".", ".."])
where f True = "Directory is empty" f False = "Directory is not empty"
main = getArgs >>= isEmpty . (!! 0) >>= putStrLn</lang> Test: <lang>$ mkdir 1 $ ./isempty 1 Directory is empty $ ./isempty /usr/ Directory is not empty</lang>
Icon and Unicon
This example uses Unicon extensions. The 'empty' sub-directory was manually setup for this test. <lang Icon>procedure main()
every dir := "." | "./empty" do write(dir, if isdirempty(dir) then " is empty" else " is not empty")
end
procedure isdirempty(s) #: succeeds if directory s is empty (and a directory) local d,f
if ( stat(s).mode ? ="d" ) & ( d := open(s) ) then { while f := read(d) do if f == ("."|"..") then next else fail close(d) return s } else stop(s," is not a directory or will not open")
end</lang>
- Output:
. is not empty ./empty is empty
J
<lang j>require 'dir' empty_dir=: 0 = '/*' #@dir@,~ ]</lang>
In other words, list the contents of the directory, count how many items are in it, and test if that count was zero.
Note that 1!:0
could have been used here, instead of the dir
cover.
Example, under windows, create some directories using cygwin:
<lang bash>$ mkdir /tmp/a $ touch /tmp/a/... $ mkdir /tmp/b $ mkdir /tmp/c $ mkdir /tmp/c/d</lang>
Then, testing these directories, in J:
<lang j> empty_dir 'c:/cygwin/tmp/a' 0
empty_dir 'c:/cygwin/tmp/b'
1
empty_dir 'c:/cygwin/tmp/c'
0</lang>
Java
This method does not check that the path given is actually a directory. If a path to a normal file is given, it will throw a NullPointerException
. File.listFiles()
does not count the "." and ".." entries.
<lang java5>import java.nio.file.Paths;
//... other class code here
public static boolean isEmptyDir(String dirName){
return Paths.get(dirName).toFile().listFiles().length == 0;
}</lang>
Lasso
<lang Lasso>dir('has_content') -> isEmpty
'
'
dir('no_content') -> isEmpty</lang>
- Output:
false true
Liberty BASIC
<lang lb> dim info$(10, 10) files "c:\", info$()
qtyFiles=val(info$(0,0)) n = qtyFiles+1 'begin directory info
folder$ = info$(n,0) 'path to first directory in c:
files folder$, info$() 're-fill array with data from sub folder
if val(info$(0,0)) + val(info$(0, 1)) <> 0 then
print "Folder ";folder$;" is not empty."
else
print "Folder ";folder$;" is empty."
end if </lang>
Mathematica
<lang Mathematica>EmptyDirectoryQ[x_] := (SetDirectory[x]; If[FileNames[] == {}, True, False])
Example use: EmptyDirectoryQ["C:\\Program Files\\Wolfram Research\\Mathematica\\9"] ->True</lang>
MATLAB / Octave
<lang Matlab>
function x = isEmptyDirectory(p) if isdir(p) f = dir(p) x = length(f)>2; else error('Error: %s is not a directory'); end; end;
</lang>
Nemerle
<lang Nemerle>using System.IO; using System.Console;
module EmptyDirectory {
IsDirectoryEmpty(dir : string) : bool { Directory.GetFileSystemEntries(dir).Length == 0 } Main(args : array[string]) : void { foreach (dir in args) { when (Directory.Exists(dir)) { WriteLine("{0} {1} empty.", dir, if (IsDirectoryEmpty(dir)) "is" else "is not"); } } }
}</lang>
Nim
<lang nim>import os, rdstdin
var empty = true for f in walkDir(readLineFromStdin "directory: "):
empty = false break
echo empty</lang>
OCaml
<lang ocaml>let is_dir_empty d =
Sys.readdir d = [| |]</lang>
Perl
Simple version
<lang perl>sub dir_is_empty {!<$_[0]/*>}</lang> This version however doesn't catch 'hidden' files that start with a dot.
May be good for quick one-liners or in some special cases when you are sure that there are no 'hidden' files or they doesn't play any role.
Unfortunalety, BSD glob() doesn't handle inverted character class. If it did, this pattern could be used: {.[^.],}* (this works well in bash). But it doesn't, so there's a
Thorough version
<lang perl>use IO::Dir; sub dir_is_empty { !grep !/^\.{1,2}\z/, IO::Dir->new(@_)->read }</lang>
Perl 6
<lang perl6>sub dir-is-empty ($d) { not dir $d }</lang> The dir function returns a lazy list of filenames, excluding "." and ".." automatically. Any boolean context (in this case the not function) will do just enough work on the lazy list to determine whether there are any elements, so we don't have to count the directory entries, or even read them all into memory, if there are more than one buffer's worth.
PHP
Any improvements welcome but here is a starting point for PHP <lang php>
$dir = 'path_here';
if(is_dir($dir)){
//scandir grabs the contents of a directory and array_diff is being used to filter out .. and . $list = array_diff(scandir($dir), array('..', '.')); //now we can just use empty to check if the variable has any contents regardless of it's type if(empty($list)){ echo 'dir is empty'; } else{ echo 'dir is not empty'; }
} else{
echo 'not a directory';
}
</lang>
PicoLisp
<lang PicoLisp>(prinl "myDir is" (and (dir "myDir") " not") " empty")</lang>
- Output:
myDir is not empty
PureBasic
<lang purebasic>Procedure isDirEmpty(path$)
If Right(path$, 1) <> "\": path$ + "\": EndIf Protected dirID = ExamineDirectory(#PB_Any, path$, "*.*") Protected result If dirID result = 1 While NextDirectoryEntry(dirID) If DirectoryEntryType(dirID) = #PB_DirectoryEntry_File Or (DirectoryEntryName(dirID) <> "." And DirectoryEntryName(dirID) <> "..") result = 0 Break EndIf Wend FinishDirectory(dirID) EndIf ProcedureReturn result
EndProcedure
Define path$, result$
path$ = PathRequester("Choose a path", "C:\") If path$
If isDirEmpty(path$) result$ = " is empty." Else result$ = " is not empty." EndIf MessageRequester("Empty directory test", #DQUOTE$ + path$ + #DQUOTE$ + result$)
EndIf </lang>
- Output:
when selecting directories "L
"L:\vv\6\" is empty. "L:\vv\" is not empty.
PowerShell
<lang PowerShell> $path = "C:\Users" if((Dir $path).Count -eq 0) {
"$path is empty"
} else {
"$path is not empty"
} </lang> Output:
C:\Users is not empty
Python
<lang python>import os; if os.listdir(raw_input("directory")):
print "not empty"
else:
print "empty"
</lang>
Racket
<lang racket>
- lang racket
(empty? (directory-list "some-directory")) </lang>
REXX
The following program was tested in a DOS window under Windows/XP and should work for all Microsoft Windows. <lang rexx>/*REXX pgm checks to see if a directory is empty; if not, lists entries.*/ parse arg xdir; if xdir= then xdir='\someDir' /*Any DIR? Use default.*/ @.=0 /*default in case ADDRESS fails. */ trace off /*suppress REXX err msg for fails*/ address system 'DIR' xdir '/b' with output stem @. /*issue the DIR cmd.*/ if rc\==0 then do /*an error happened?*/
say '***error!*** from DIR' xDIR /*indicate que pasa.*/ say 'return code=' rc /*show the ret Code.*/ exit rc /*exit with the RC.*/ end /* [↑] bad address.*/
- =@.rc /*number of entries.*/
if #==0 then #=' no ' /*use a word, ¬zero.*/ say center('directory ' xdir " has " # ' entries.',79,'─') exit @.0+rc /*stick a fork in it, we're done.*/</lang>
- Output:
when the following input was used
──────────────────────directory temp has 10 entries.───────────────────────
- Output:
when the following input was used
───────────────────directory \someDir has no entries.───────────────────
Ruby
Raises a SystemCallError if the named directory doesn’t exist. <lang ruby>Dir.entries("testdir").empty? </lang>
Run BASIC
<lang runbasic>files #f, DefaultDir$ + "\*.*" ' open some directory.
print "hasanswer: ";#f HASANSWER() ' if it has an answer it is not MT print "rowcount: ";#f ROWCOUNT() ' if not MT, how many files?</lang>
Scala
<lang scala>import java.io.File
def isDirEmpty(file:File) : Boolean =
return file.exists && file.isDirectory && file.list.isEmpty</lang>
Seed7
<lang seed7>$ include "seed7_05.s7i";
include "osfiles.s7i";
const func boolean: dirEmpty (in string: dirName) is
return fileType(dirName) = FILE_DIR and length(readDir(dirName)) = 0;
const proc: main is func
begin writeln(dirEmpty("somedir")); end func;</lang>
Sidef
Built-in method: <lang ruby>Dir.new('/my/dir').is_empty; # true, false or nil</lang>
User-defined function: <lang ruby>func is_empty(dir) {
dir.open(\var dir_h) || return nil; dir_h.each { |file| file ~~ ['.', '..'] && next; return false; }; return true;
};</lang>
Tcl
<lang tcl>proc isEmptyDir {dir} {
# Get list of _all_ files in directory set filenames [glob -nocomplain -tails -directory $dir * .*] # Check whether list is empty (after filtering specials) expr {![llength [lsearch -all -not -regexp $filenames {^\.\.?$}]]}
}</lang>
UNIX Shell
<lang bash>
- !/bin/sh
DIR=/tmp/foo [ `ls -a $DIR|wc -l` -gt 2 ] && echo $DIR is NOT empty || echo $DIR is empty </lang>
zkl
<lang zkl>path:="Empty"; File.isDir(path).println(); File.mkdir(path); File.isDir(path).println(); File.glob(path+"/*").println(); // show contents of directory</lang>
- Output:
False True L()
- Programming Tasks
- Solutions by Programming Task
- Ada
- AutoHotkey
- BBC BASIC
- C
- C++
- Boost
- C sharp
- Clojure
- CoffeeScript
- Common Lisp
- D
- Erlang
- F Sharp
- Go
- Groovy
- Haskell
- Unicon
- J
- Java
- Lasso
- Liberty BASIC
- Mathematica
- MATLAB
- Octave
- Nemerle
- Nim
- OCaml
- Perl
- Perl 6
- PHP
- PicoLisp
- PureBasic
- PowerShell
- Python
- Racket
- REXX
- Ruby
- Run BASIC
- Scala
- Seed7
- Sidef
- Tcl
- UNIX Shell
- Zkl
- ACL2/Omit