Empty directory
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.
C
<lang c>#include <stdio.h>
- include <dirent.h>
- include <string.h>
int dir_empty(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
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>
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.
Example, under windows, create some directories:
<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>
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> Sample output when selecting directories "L:\vv\6\" and "L:\vv\" :
"L:\vv\6\" is empty. "L:\vv\" is not empty.
Python
<lang python>import os; if os.listdir(raw_input("directory")):
print "not empty"
else:
print "empty"
</lang>
Ruby
<lang ruby># Checks if a directory is empty, but raises SystemCallError
- if _path_ is not a directory.
def empty_dir?(path)
not Dir.foreach(path).detect {|f| f != '.' and f != '..'}
end</lang>
If Ruby is older than 1.8.7, then Dir.foreach must take a block.
<lang ruby># Checks if a directory is empty, but raises SystemCallError
- if _path_ is not a directory.
def empty_dir?(path)
Dir.foreach(path) {|f| return false if f != '.' and f != '..' } return true
end</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>