Empty directory: Difference between revisions

From Rosetta Code
Content added Content deleted
(Added Prolog)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(35 intermediate revisions by 19 users not shown)
Line 6: Line 6:


=={{header|11l}}==
=={{header|11l}}==
<lang 11l>I fs:list_dir(input()).empty
<syntaxhighlight lang="11l">I fs:list_dir(input()).empty
print(‘empty’)
print(‘empty’)
E
E
print(‘not empty’)</lang>
print(‘not empty’)</syntaxhighlight>

=={{header|8086 Assembly}}==
{{trans|MS-DOS}}

<syntaxhighlight lang="asm">; this routine attempts to remove the directory and returns an error code if it cannot.

mov ax,seg dirname ;load into AX the segment where dirname is stored.
mov ds,ax ;load the segment register DS with the segment of dirname
mov dx,offset dirname ;load into DX the offset of dirname
mov ah,39h ;0x39 is the interrupt code for remove directory
int 21h ;sets carry if error is encountered. error code will be in AX.
;If carry is clear the remove was successful

jc error

mov ah,4Ch ;return function
mov al,0 ;required return code
int 21h ;return to DOS

error: ;put your error handler here

mov ah,4Ch ;return function
mov al,0 ;required return code
int 21h ;return to DOS


dirname db "GAMES",0</syntaxhighlight>


=={{header|Ada}}==
=={{header|Ada}}==
<lang Ada>with Ada.Text_IO; use Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;
with Ada.Directories;
with Ada.Directories;
procedure EmptyDir is
procedure EmptyDir is
Line 35: Line 62:
Put_Line (Empty ("./emptydir.adb"));
Put_Line (Empty ("./emptydir.adb"));
Put_Line (Empty ("./foobar"));
Put_Line (Empty ("./foobar"));
end EmptyDir;</lang>
end EmptyDir;</syntaxhighlight>
{{out}}
{{out}}
<pre>Not empty
<pre>Not empty
Line 46: Line 73:
This uses the "argc", "argv", "file is directory" and "get directory" procedures specific to Algol 68 G.
This uses the "argc", "argv", "file is directory" and "get directory" procedures specific to Algol 68 G.
<br>Note the Algol 68 G interpreter processes the command line parameters before "-" so this example expects the directory names to follow "-".
<br>Note the Algol 68 G interpreter processes the command line parameters before "-" so this example expects the directory names to follow "-".
<lang algol68># returns TRUE if the specified directory is empty, FALSE if it doesn't exist or is non-empty #
<syntaxhighlight lang="algol68"># returns TRUE if the specified directory is empty, FALSE if it doesn't exist or is non-empty #
PROC is empty directory = ( STRING directory )BOOL:
PROC is empty directory = ( STRING directory )BOOL:
IF NOT file is directory( directory )
IF NOT file is directory( directory )
Line 77: Line 104:
print( ( argv( i ), " is ", IF is empty directory( argv( i ) ) THEN "empty" ELSE "not empty" FI, newline ) )
print( ( argv( i ), " is ", IF is empty directory( argv( i ) ) THEN "empty" ELSE "not empty" FI, newline ) )
FI
FI
OD</lang>
OD</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 85: Line 112:
\zz is empty
\zz is empty
</pre>
</pre>

=={{header|Arturo}}==

<syntaxhighlight lang="rebol">emptyDir?: function [folder]-> empty? list folder

print emptyDir? "."</syntaxhighlight>

{{out}}

<pre>false</pre>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang autohotkey>MsgBox % isDir_empty(A_ScriptDir)?"true":"false"
<syntaxhighlight lang="autohotkey">MsgBox % isDir_empty(A_ScriptDir)?"true":"false"


isDir_empty(p) {
isDir_empty(p) {
Line 93: Line 130:
return 0
return 0
return 1
return 1
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>false</pre>
<pre>false</pre>

=={{header|AWK}}==
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f EMPTY_DIRECTORY.AWK
# syntax: GAWK -f EMPTY_DIRECTORY.AWK
BEGIN {
BEGIN {
Line 135: Line 173:
return(msg)
return(msg)
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 144: Line 182:
</pre>
</pre>


=={{header|BaCon}}==
=={{header|BASIC}}==
==={{header|BaCon}}===
<lang freebasic>' empty directory test
<syntaxhighlight lang="basic">FUNCTION check$(dir$)
somedir$ = "somedir"
files = testdir(somedir$)
IF files = 0 THEN PRINT somedir$, " directory empty"


IF FILEEXISTS(dir$) THEN
files = testdir(".")
RETURN IIF$(LEN(WALK$(dir$, 127, ".+", FALSE)), " is NOT empty.", " is empty." )
PRINT "Current directory holds ", files, " files"
ELSE
END
RETURN " doesn't exist."
ENDIF


ENDFUNCTION
FUNCTION testdir(somedir$)

OPEN somedir$ FOR DIRECTORY AS adir
dir$ = "bla"
total = 0
PRINT "Directory '", dir$, "'", check$(dir$)
REPEAT

GETFILE afile$ FROM adir
dir$ = "/mnt"
IF afile$ != "." AND afile$ != ".." AND afile$ != "" THEN INCR total
PRINT "Directory '", dir$, "'", check$(dir$)
UNTIL ISFALSE(LEN(afile$))

IF (long)adir != 0 THEN CLOSE DIRECTORY adir
dir$ = "."
RETURN total
PRINT "Directory '", dir$, "'", check$(dir$)</syntaxhighlight>
END FUNCTION</lang>


{{out}}
{{out}}
<pre>Directory 'bla' doesn't exist.
<pre>prompt$ ./empty-dir
somedir directory empty
Directory '/mnt' is empty.
Current directory holds 183 files</pre>
Directory '.' is NOT empty.</pre>


=={{header|Batch File}}==
=={{header|Batch File}}==
Line 176: Line 214:
*2 - input directory does not exist.
*2 - input directory does not exist.
*3 - input not found.
*3 - input not found.
<lang dos>@echo off
<syntaxhighlight lang="dos">@echo off
if "%~1"=="" exit /b 3
if "%~1"=="" exit /b 3
set "samp_path=%~1"
set "samp_path=%~1"
Line 205: Line 243:
:folder_not_found
:folder_not_found
echo Folder not found.
echo Folder not found.
exit /b 2</lang>
exit /b 2</syntaxhighlight>
{{Out|Sample Session}}
{{Out|Sample Session}}
(Saved the Batch File as IsEmpty.Bat in C:\)
(Saved the Batch File as IsEmpty.Bat in C:\)
Line 237: Line 275:
=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
<lang bbcbasic> IF FNisdirectoryempty("C:\") PRINT "C:\ is empty" ELSE PRINT "C:\ is not empty"
<syntaxhighlight 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"
IF FNisdirectoryempty("C:\temp") PRINT "C:\temp is empty" ELSE PRINT "C:\temp is not empty"
END
END
Line 253: Line 291:
UNTIL res% == 0
UNTIL res% == 0
SYS "FindClose", sh%
SYS "FindClose", sh%
= (res% == 0)</lang>
= (res% == 0)</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <dirent.h>
#include <dirent.h>
#include <string.h>
#include <string.h>
Line 295: Line 333:


return 0;
return 0;
}</lang>Running it:<pre>
}</syntaxhighlight>Running it:<pre>
% mkdir stuff; ./a.out /usr/ ./stuff /etc/passwd
% mkdir stuff; ./a.out /usr/ ./stuff /etc/passwd
/usr/: not empty
/usr/: not empty
Line 302: Line 340:
</pre>
</pre>


=={{header|C++}}==
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">using System;
{{libheader|Boost}}
<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>

=={{header|C sharp}}==
<lang csharp>using System;
using System.IO;
using System.IO;


Line 343: Line 360:
}
}
}
}
</syntaxhighlight>
</lang>
Running it:<pre>
Running it:<pre>
Assume c:\temp exists and is not empty, c:\temp\empty exists and is empty
Assume c:\temp exists and is not empty, c:\temp\empty exists and is empty
Line 351: Line 368:
'c:\temp\empty' is empty
'c:\temp\empty' is empty
</pre>
</pre>

=={{header|C++}}==
{{libheader|Boost}}
<syntaxhighlight 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";
}
}
</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang clojure>(require '[clojure.java.io :as io])
<syntaxhighlight lang="clojure">(require '[clojure.java.io :as io])
(defn empty-dir? [path]
(defn empty-dir? [path]
(let [file (io/file path)]
(let [file (io/file path)]
(assert (.exists file))
(assert (.exists file))
(assert (.isDirectory file))
(assert (.isDirectory file))
(-> file .list empty?))) ; .list ignores "." and ".."</lang>
(-> file .list empty?))) ; .list ignores "." and ".."</syntaxhighlight>



=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
<lang coffeescript>
<syntaxhighlight lang="coffeescript">
fs = require 'fs'
fs = require 'fs'


Line 370: Line 407:
fns = fs.readdirSync dir
fns = fs.readdirSync dir
fns.length == 0
fns.length == 0
</syntaxhighlight>
</lang>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
Will also return <code>T</code> if <code>path</code> doesn't exist.
Will also return <code>T</code> if <code>path</code> doesn't exist.
<lang lisp>
<syntaxhighlight lang="lisp">
(defun empty-directory-p (path)
(defun empty-directory-p (path)
(and (null (directory (concatenate 'string path "/*")))
(and (null (directory (concatenate 'string path "/*")))
(null (directory (concatenate 'string path "/*/")))))
(null (directory (concatenate 'string path "/*/")))))
</syntaxhighlight>
</lang>


=={{header|D}}==
=={{header|D}}==


<lang d>import std.stdio, std.file;
<syntaxhighlight lang="d">import std.stdio, std.file;


void main() {
void main() {
Line 393: Line 430:
throw new Exception("dir not found: " ~ dirname);
throw new Exception("dir not found: " ~ dirname);
return dirEntries(dirname, SpanMode.shallow).empty;
return dirEntries(dirname, SpanMode.shallow).empty;
}</lang>
}</syntaxhighlight>
<pre>somedir is empty: false</pre>
<pre>somedir is empty: false</pre>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| System.IOUtils}}
{{Trans|C#}}
<syntaxhighlight lang="delphi">
program Empty_directory;


{$APPTYPE CONSOLE}

uses
System.SysUtils,
System.IOUtils;

function IsDirectoryEmpty(dir: string): Boolean;
var
count: Integer;
begin
count := Length(TDirectory.GetFiles(dir)) + Length(TDirectory.GetDirectories(dir));
Result := count = 0;
end;

var
i: Integer;

const
CHECK: array[Boolean] of string = (' is not', ' is');

begin
if ParamCount > 0 then
for i := 1 to ParamCount do
Writeln(ParamStr(i), CHECK[IsDirectoryEmpty(ParamStr(i))], ' empty');
Readln;
end.</syntaxhighlight>
{{out}}
The same of c#.
=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>path = hd(System.argv)
<syntaxhighlight lang="elixir">path = hd(System.argv)
IO.puts File.dir?(path) and Enum.empty?( File.ls!(path) )</lang>
IO.puts File.dir?(path) and Enum.empty?( File.ls!(path) )</syntaxhighlight>


=={{header|Erlang}}==
=={{header|Erlang}}==
Line 413: Line 484:
{ok,[]}
{ok,[]}
</pre>
</pre>

=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="fsharp">open System.IO
let isEmptyDirectory x = (Directory.GetFiles x).Length = 0 && (Directory.GetDirectories x).Length = 0</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>USE: io.directories
<syntaxhighlight lang="factor">USE: io.directories
: empty-directory? ( path -- ? ) directory-entries empty? ;</lang>
: empty-directory? ( path -- ? ) directory-entries empty? ;</syntaxhighlight>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


#Include "dir.bi"
#Include "dir.bi"
Line 461: Line 536:
Print
Print
Print "Press any key to quit"
Print "Press any key to quit"
Sleep</lang>
Sleep</syntaxhighlight>


{{out}}
{{out}}
Line 468: Line 543:
</pre>
</pre>


=={{header|F_Sharp|F#}}==
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
<lang fsharp>open System.IO

let isEmptyDirectory x = (Directory.GetFiles x).Length = 0 && (Directory.GetDirectories x).Length = 0</lang>
include "NSLog.incl"

local fn DirectoryContents( url as CFURLRef ) as CFArrayRef
CFArrayRef contents = fn FileManagerContentsOfDirectoryAtURL( url, NULL, NSDirectoryEnumerationSkipsHiddenFiles )
if ( contents == NULL )
NSLog(@"Unable to get contents of directory \"%@\".",fn URLLastPathComponent(url))
end if
end fn = fn ArrayValueForKey( contents, @"lastPathComponent" )

void local fn DoIt
CFURLRef dirURL, fileURL
CFArrayRef contents
dirURL = fn URLFileURLWithPath( fn StringByExpandingTildeInPath( @"~/Desktop/docs" ) )
if ( fn FileManagerCreateDirectoryAtURL( dirURL, YES, NULL ) )
contents = fn DirectoryContents( dirURL )
if ( contents )
NSLog(@"Directory \"docs\" \b")
if ( len(contents) )
NSLog(@"contents:\n%@",contents)
else
NSLog(@"is empty.")
end if
NSLog(@"")
fileURL = fn URLFileURLWithPath( fn StringByExpandingTildeInPath( @"~/Desktop/docs/output.txt" ) )
if (fn FileManagerCreateFileAtURL( fileURL, NULL, NULL ) )
contents = fn DirectoryContents( dirURL )
NSLog(@"Directory \"docs\" \b")
if ( len(contents) )
NSLog(@"contents:\n%@",contents)
else
NSLog(@"is empty.")
end if
end if
end if
end if
end fn

fn DoIt

HandleEvents
</syntaxhighlight>

{{out}}
<pre>
Directory "docs" is empty.

Directory "docs" contents:
(
"output.txt"
)
</pre>


=={{header|Gambas}}==
=={{header|Gambas}}==
<lang gambas>Public Sub Main()
<syntaxhighlight lang="gambas">Public Sub Main()
Dim sFolder As String = User.home &/ "Rosetta"
Dim sFolder As String = User.home &/ "Rosetta"
Dim sDir As String[] = Dir(sFolder)
Dim sDir As String[] = Dir(sFolder)
Line 484: Line 614:
Print sOutput
Print sOutput


End</lang>
End</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 491: Line 621:


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 518: Line 648:
return len(entries) == 0, nil
return len(entries) == 0, nil
}
}
</syntaxhighlight>
</lang>

=={{header|Groovy}}==
=={{header|Groovy}}==
Solution:
Solution:
<lang groovy>def isDirEmpty = { dirName ->
<syntaxhighlight lang="groovy">def isDirEmpty = { dirName ->
def dir = new File(dirName)
def dir = new File(dirName)
dir.exists() && dir.directory && (dir.list() as List).empty
dir.exists() && dir.directory && (dir.list() as List).empty
}</lang>
}</syntaxhighlight>


Test:
Test:
<lang groovy>def currentDir = new File('.')
<syntaxhighlight lang="groovy">def currentDir = new File('.')
def random = new Random()
def random = new Random()
def subDirName = "dir${random.nextInt(100000)}"
def subDirName = "dir${random.nextInt(100000)}"
Line 535: Line 666:


assert ! isDirEmpty('.')
assert ! isDirEmpty('.')
assert isDirEmpty(subDirName)</lang>
assert isDirEmpty(subDirName)</syntaxhighlight>


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>import System.Directory (getDirectoryContents)
<syntaxhighlight lang="haskell">import System.Directory (getDirectoryContents)
import System.Environment (getArgs)
import System.Environment (getArgs)


Line 546: Line 677:
f False = "Directory is not empty"
f False = "Directory is not empty"


main = getArgs >>= isEmpty . (!! 0) >>= putStrLn</lang>
main = getArgs >>= isEmpty . (!! 0) >>= putStrLn</syntaxhighlight>
Test:
Test:
<lang>$ mkdir 1
<syntaxhighlight lang="text">$ mkdir 1
$ ./isempty 1
$ ./isempty 1
Directory is empty
Directory is empty
$ ./isempty /usr/
$ ./isempty /usr/
Directory is not empty</lang>
Directory is not empty</syntaxhighlight>




==Icon and {{header|Unicon}}==
==Icon and {{header|Unicon}}==
This example uses Unicon extensions. The 'empty' sub-directory was manually setup for this test.
This example uses Unicon extensions. The 'empty' sub-directory was manually setup for this test.
<lang Icon>procedure main()
<syntaxhighlight lang="icon">procedure main()
every dir := "." | "./empty" do
every dir := "." | "./empty" do
write(dir, if isdirempty(dir) then " is empty" else " is not empty")
write(dir, if isdirempty(dir) then " is empty" else " is not empty")
Line 571: Line 702:
}
}
else stop(s," is not a directory or will not open")
else stop(s," is not a directory or will not open")
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 579: Line 710:
=={{header|J}}==
=={{header|J}}==


<lang j>require 'dir'
<syntaxhighlight lang="j">require 'dir'
empty_dir=: 0 = '/*' #@dir@,~ ]</lang>
empty_dir=: 0 = '/*' #@dir@,~ ]</syntaxhighlight>


In other words, list the contents of the directory, count how many items are in it, and test if that count was zero.
In other words, list the contents of the directory, count how many items are in it, and test if that count was zero.
Line 588: Line 719:
Example, under windows, create some directories using cygwin:
Example, under windows, create some directories using cygwin:


<lang bash>$ mkdir /tmp/a
<syntaxhighlight lang="bash">$ mkdir /tmp/a
$ touch /tmp/a/...
$ touch /tmp/a/...
$ mkdir /tmp/b
$ mkdir /tmp/b
$ mkdir /tmp/c
$ mkdir /tmp/c
$ mkdir /tmp/c/d</lang>
$ mkdir /tmp/c/d</syntaxhighlight>


Then, testing these directories, in J:
Then, testing these directories, in J:


<lang j> empty_dir 'c:/cygwin/tmp/a'
<syntaxhighlight lang="j"> empty_dir 'c:/cygwin/tmp/a'
0
0
empty_dir 'c:/cygwin/tmp/b'
empty_dir 'c:/cygwin/tmp/b'
1
1
empty_dir 'c:/cygwin/tmp/c'
empty_dir 'c:/cygwin/tmp/c'
0</lang>
0</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
{{works with|Java|7+}}
{{works with|Java|7+}}
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 <code>NullPointerException</code>. <code>File.listFiles()</code> does not count the "." and ".." entries.
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 <code>NullPointerException</code>. <code>File.listFiles()</code> does not count the "." and ".." entries.
<lang java5>import java.nio.file.Paths;
<syntaxhighlight lang="java5">import java.nio.file.Paths;
//... other class code here
//... other class code here
public static boolean isEmptyDir(String dirName){
public static boolean isEmptyDir(String dirName){
return Paths.get(dirName).toFile().listFiles().length == 0;
return Paths.get(dirName).toFile().listFiles().length == 0;
}</lang>
}</syntaxhighlight>

=={{header|JavaScript}}==
The ECMAScript standard itself defines no IO interface – the following example makes use of the Node.js file IO library.
{{Works with|Node.js}}
<syntaxhighlight lang="javascript">// Node.js v14.15.4
const { readdirSync } = require("fs");
const emptydir = (path) => readdirSync(path).length == 0;

// tests, run like node emptydir.js [directories]
for (let i = 2; i < process.argv.length; i ++) {
let dir = process.argv[i];
console.log(`${dir}: ${emptydir(dir) ? "" : "not "}empty`)
}</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==
<lang julia># v0.6.0
<syntaxhighlight lang="julia"># v0.6.0
isemptydir(dir::AbstractString) = isempty(readdir(dir))
isemptydir(dir::AbstractString) = isempty(readdir(dir))


@show isemptydir(".")
@show isemptydir(".")
@show isemptydir("/home")
@show isemptydir("/home")
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 627: Line 771:


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.1.4
<syntaxhighlight lang="scala">// version 1.1.4


import java.io.File
import java.io.File
Line 635: Line 779:
val isEmpty = (File(dirPath).list().isEmpty())
val isEmpty = (File(dirPath).list().isEmpty())
println("$dirPath is ${if (isEmpty) "empty" else "not empty"}")
println("$dirPath is ${if (isEmpty) "empty" else "not empty"}")
}</lang>
}</syntaxhighlight>


=={{header|Lasso}}==
=={{header|Lasso}}==
<lang Lasso>dir('has_content') -> isEmpty
<syntaxhighlight lang="lasso">dir('has_content') -> isEmpty
'<br />'
'<br />'
dir('no_content') -> isEmpty</lang>
dir('no_content') -> isEmpty</syntaxhighlight>
{{out}}
{{out}}
<pre>false
<pre>false
Line 646: Line 790:


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
dim info$(10, 10)
dim info$(10, 10)
files "c:\", info$()
files "c:\", info$()
Line 662: Line 806:
print "Folder ";folder$;" is empty."
print "Folder ";folder$;" is empty."
end if
end if
</syntaxhighlight>
</lang>


=={{header|Lingo}}==
=={{header|Lingo}}==
<lang lingo>on isDirEmpty (dir)
<syntaxhighlight lang="lingo">on isDirEmpty (dir)
return getNthFileNameInFolder(dir, 1) = EMPTY
return getNthFileNameInFolder(dir, 1) = EMPTY
end</lang>
end</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
Pure Lua function based on snipplet from Stack Overflow[http://stackoverflow.com/questions/5303174/how-to-get-list-of-directories-in-lua#11130774].
Pure Lua function based on snipplet from Stack Overflow[http://stackoverflow.com/questions/5303174/how-to-get-list-of-directories-in-lua#11130774].
<lang lua>
<syntaxhighlight lang="lua">
function scandir(directory)
function scandir(directory)
local i, t, popen = 0, {}, io.popen
local i, t, popen = 0, {}, io.popen
Line 688: Line 832:
return #scandir(directory) == 0
return #scandir(directory) == 0
end
end
</syntaxhighlight>
</lang>


Using lfs[https://keplerproject.github.io/luafilesystem/] library.
Using lfs[https://keplerproject.github.io/luafilesystem/] library.
<lang lua>
<syntaxhighlight lang="lua">
function isemptydir(directory,nospecial)
function isemptydir(directory,nospecial)
for filename in require('lfs').dir(directory) do
for filename in require('lfs').dir(directory) do
Line 700: Line 844:
return true
return true
end
end
</syntaxhighlight>
</lang>


=={{header|Maple}}==
=={{header|Maple}}==


<syntaxhighlight lang="maple">
<lang Maple>
emptydirectory := proc (dir)
emptydirectory := proc (dir)
is(listdir(dir) = [".", ".."]);
is(listdir(dir) = [".", ".."]);
end proc;
end proc;
</syntaxhighlight>
</lang>



=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<lang Mathematica>EmptyDirectoryQ[x_] := (SetDirectory[x]; If[FileNames[] == {}, True, False])
<syntaxhighlight lang="mathematica">EmptyDirectoryQ[x_] := (SetDirectory[x]; If[FileNames[] == {}, True, False])


Example use:
Example use:
EmptyDirectoryQ["C:\\Program Files\\Wolfram Research\\Mathematica\\9"]
EmptyDirectoryQ["C:\\Program Files\\Wolfram Research\\Mathematica\\9"]
->True</lang>
->True</syntaxhighlight>


=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==
<syntaxhighlight lang="matlab">
<lang Matlab>
function x = isEmptyDirectory(p)
function x = isEmptyDirectory(p)
if isdir(p)
if isdir(p)
Line 728: Line 871:
end;
end;
end;
end;
</syntaxhighlight>
</lang>


=={{header|min}}==
=={{header|min}}==
{{works with|min|0.19.3}}
{{works with|min|0.19.3}}
<lang min>(ls bool not) :empty-dir?</lang>
<syntaxhighlight lang="min">(ls bool not) :empty-dir?</syntaxhighlight>

=={{header|MS-DOS}}==

Since you cannot remove a directory that isn't empty, one way to check is to attempt to remove it.
<syntaxhighlight lang="dos">C:\>rd GAMES
Unable to remove: GAMES.

C:\></syntaxhighlight>
=={{header|Nanoquery}}==
<syntaxhighlight lang="nanoquery">def isempty(dirname)
return len(new(Nanoquery.IO.File).listDir(dirname)) = 0
end</syntaxhighlight>


=={{header|Nemerle}}==
=={{header|Nemerle}}==
<lang Nemerle>using System.IO;
<syntaxhighlight lang="nemerle">using System.IO;
using System.Console;
using System.Console;


Line 753: Line 908:
}
}
}
}
}</lang>
}</syntaxhighlight>



=={{header|NewLISP}}==
=={{header|NewLISP}}==
<syntaxhighlight lang="newlisp">
<lang NewLISP>
(define (empty-dir? path-to-check)
(define (empty-dir? path-to-check)
(empty? (clean (lambda (x) (or (= "." x) (= ".." x))) (directory path-to-check)))
(empty? (clean (lambda (x) (or (= "." x) (= ".." x))) (directory path-to-check)))
)
)
</syntaxhighlight>
</lang>


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>import os, rdstdin
<syntaxhighlight lang="nim">import os, rdstdin


var empty = true
var empty = true
Line 770: Line 924:
empty = false
empty = false
break
break
echo empty</lang>
echo empty</syntaxhighlight>

Alternatively:

<syntaxhighlight lang="nim">import os, sequtils

proc isEmptyDir(dir: string): bool =
toSeq(walkdir dir).len == 0

echo isEmptyDir("/tmp") # false - there is always something in "/tmp"
echo isEmptyDir("/temp") # true - "/temp" does not exist</syntaxhighlight>


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>function : IsEmptyDirectory(dir : String) ~ Bool {
<syntaxhighlight lang="objeck">function : IsEmptyDirectory(dir : String) ~ Bool {
return Directory->List(dir)->Size() = 0;
return Directory->List(dir)->Size() = 0;
}</lang>
}</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==


<lang ocaml>let is_dir_empty d =
<syntaxhighlight lang="ocaml">let is_dir_empty d =
Sys.readdir d = [| |]</lang>
Sys.readdir d = [| |]</syntaxhighlight>


=={{header|ooRexx}}==
=={{header|ooRexx}}==
<lang oorexx>Call test 'D:\nodir' /* no such directory */
<syntaxhighlight lang="oorexx">Call test 'D:\nodir' /* no such directory */
Call test 'D:\edir' /* an empty directory */
Call test 'D:\edir' /* an empty directory */
Call test 'D:\somedir' /* directory with 2 files */
Call test 'D:\somedir' /* directory with 2 files */
Line 802: Line 966:
End
End
End
End
Return</lang>
Return</syntaxhighlight>
{{out}}
{{out}}
<pre>Directory D:\nodir not found
<pre>Directory D:\nodir not found
Line 812: Line 976:


Define a function ''chkdir(<path>)'' that returns count of entries in a directory (without . and .. ):
Define a function ''chkdir(<path>)'' that returns count of entries in a directory (without . and .. ):
<lang parigp>chkdir(d)=extern(concat(["[ -d '",d,"' ]&&ls -A '",d,"'|wc -l||echo -1"]))</lang>
<syntaxhighlight lang="parigp">chkdir(d)=extern(concat(["[ -d '",d,"' ]&&ls -A '",d,"'|wc -l||echo -1"]))</syntaxhighlight>


On error ''chkdir(...)'' returns -1 else count of entries. If ''chkdir() == 0'' then directory is empty. So define an additional function:
On error ''chkdir(...)'' returns -1 else count of entries. If ''chkdir() == 0'' then directory is empty. So define an additional function:
<lang parigp>dir_is_empty(d)=!chkdir(d)</lang>
<syntaxhighlight lang="parigp">dir_is_empty(d)=!chkdir(d)</syntaxhighlight>


Output:<pre>chkdir("/tmp"): 52
Output:<pre>chkdir("/tmp"): 52


dir_is_empty("/tmp"): 0</pre>
dir_is_empty("/tmp"): 0</pre>

=={{header|Pascal}}==
{{works with|GNU Pascal}}
Pascal does not know the notion of directories.
Therefore it is ''not possible'' to determine whether a directory is empty.

However, ''GNU Pascal'' provides certain extensions to [[Extended Pascal]] (ISO 10206) so it is possible nonetheless.
Note, the following solution works only on ''strictly hierarchical'' file systems.
<syntaxhighlight lang="pascal">program emptyDirectory(input, output);

type
path = string(1024);

{
\brief determines whether a (hierarchial FS) directory is empty
\param accessVia a possible route to access a directory
\return whether \param accessVia is an empty directory
}
function isEmptyDirectory(protected accessVia: path): Boolean;
var
{ NB: `file` data types without a domain type are non-standard }
directory: bindable file;
FD: bindingType;
begin
{ initialize variables }
unbind(directory);
FD := binding(directory);
FD.name := accessVia;
{ binding to directories is usually not possible }
FD.force := true;
{ the actual test }
bind(directory, FD);
FD := binding(directory);
unbind(directory);
isEmptyDirectory := FD.bound and FD.directory and (FD.links <= 2)
end;

{ === MAIN ============================================================= }
var
s: path;
begin
readLn(s);
writeLn(isEmptyDirectory(s))
end.</syntaxhighlight>
Note, symbolic links’ targets are resolved, so <tt>accessVia</tt> could in fact be a symbolic link ''to'' an empty directory.


=={{header|Perl}}==
=={{header|Perl}}==
===Simple version===
===Simple version===
<lang perl>sub dir_is_empty {!<$_[0]/*>}</lang>
<syntaxhighlight lang="perl">sub dir_is_empty {!<$_[0]/*>}</syntaxhighlight>
This version however doesn't catch 'hidden' files that start with a dot.
This version however doesn't catch 'hidden' files that start with a dot.


Line 830: Line 1,043:
Unfortunalety, BSD glob() doesn't handle inverted character class. If it did, this pattern could be used: <tt>{.[^.],}*</tt> (this works well in bash). But it doesn't, so there's a
Unfortunalety, BSD glob() doesn't handle inverted character class. If it did, this pattern could be used: <tt>{.[^.],}*</tt> (this works well in bash). But it doesn't, so there's a
===Thorough version===
===Thorough version===
<lang perl>use IO::Dir;
<syntaxhighlight lang="perl">use IO::Dir;
sub dir_is_empty { !grep !/^\.{1,2}\z/, IO::Dir->new(@_)->read }</lang>
sub dir_is_empty { !grep !/^\.{1,2}\z/, IO::Dir->new(@_)->read }</syntaxhighlight>

=={{header|Perl 6}}==
<lang perl6>sub dir-is-empty ($d) { not dir $d }</lang>
The <tt>dir</tt> function returns a lazy list of filenames, excluding "<tt>.</tt>" and "<tt>..</tt>" automatically. Any boolean context (in this case the <tt>not</tt> 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.


=={{header|Phix}}==
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(notonline)-->
<lang Phix>procedure test(string filename)
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- file i/o</span>
string msg
<span style="color: #008080;">procedure</span> <span style="color: #000000;">test</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">filename</span><span style="color: #0000FF;">)</span>
switch get_file_type(filename) do
<span style="color: #004080;">string</span> <span style="color: #000000;">msg</span>
case FILETYPE_UNDEFINED: msg = "is UNDEFINED"
<span style="color: #008080;">switch</span> <span style="color: #7060A8;">get_file_type</span><span style="color: #0000FF;">(</span><span style="color: #000000;">filename</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
case FILETYPE_NOT_FOUND: msg = "is NOT_FOUND"
<span style="color: #008080;">case</span> <span style="color: #000000;">FILETYPE_UNDEFINED</span><span style="color: #0000FF;">:</span> <span style="color: #000000;">msg</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"is UNDEFINED"</span>
case FILETYPE_FILE: msg = "is a FILE"
<span style="color: #008080;">case</span> <span style="color: #000000;">FILETYPE_NOT_FOUND</span><span style="color: #0000FF;">:</span> <span style="color: #000000;">msg</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"is NOT_FOUND"</span>
case FILETYPE_DIRECTORY:
<span style="color: #008080;">case</span> <span style="color: #004600;">FILETYPE_FILE</span><span style="color: #0000FF;">:</span> <span style="color: #000000;">msg</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"is a FILE"</span>
sequence d = dir(filename)
<span style="color: #008080;">case</span> <span style="color: #004600;">FILETYPE_DIRECTORY</span><span style="color: #0000FF;">:</span>
integer count = 0
<span style="color: #004080;">integer</span> <span style="color: #000000;">count</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">filter</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">vslice</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">dir</span><span style="color: #0000FF;">(</span><span style="color: #000000;">filename</span><span style="color: #0000FF;">),</span><span style="color: #004600;">D_NAME</span><span style="color: #0000FF;">),</span><span style="color: #008000;">"out"</span><span style="color: #0000FF;">,{</span><span style="color: #008000;">"."</span><span style="color: #0000FF;">,</span><span style="color: #008000;">".."</span><span style="color: #0000FF;">}))</span>
for i=1 to length(d) do
<span style="color: #000000;">msg</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">count</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">?</span><span style="color: #008000;">"is an empty directory"</span>
if not find(d[i][D_NAME],{".",".."}) then
<span style="color: #0000FF;">:</span><span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"is a directory containing %d files"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">count</span><span style="color: #0000FF;">}))</span>
count += 1
<span style="color: #008080;">end</span> <span style="color: #008080;">switch</span>
end if
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">filename</span><span style="color: #0000FF;">,</span><span style="color: #000000;">msg</span><span style="color: #0000FF;">})</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
if count=0 then
msg = "is an empty directory"
<span style="color: #008080;">constant</span> <span style="color: #000000;">tests</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"C:\\xx"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"C:\\not_there"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"C:\\Program Files (x86)\\Phix\\p.exe"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"C:\\Windows"</span><span style="color: #0000FF;">}</span>
else
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tests</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
msg = sprintf("is a directory containing %d files",{count})
<span style="color: #000000;">test</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tests</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end switch
<!--</syntaxhighlight>-->
printf(1,"%s %s\n",{filename,msg})
end procedure

constant tests = {"C:\\xx","C:\\not_there","C:\\Program Files (x86)\\Phix\\p.exe","C:\\Windows"}
for i=1 to length(tests) do
test(tests[i])
end for</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 875: Line 1,078:
=={{header|PHP}}==
=={{header|PHP}}==
Any improvements welcome but here is a starting point for PHP
Any improvements welcome but here is a starting point for PHP
<lang php>
<syntaxhighlight lang="php">


$dir = 'path_here';
$dir = 'path_here';
Line 894: Line 1,097:
}
}


</syntaxhighlight>
</lang>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(prinl "myDir is" (and (dir "myDir") " not") " empty")</lang>
<syntaxhighlight lang="picolisp">(prinl "myDir is" (and (dir "myDir") " not") " empty")</syntaxhighlight>
{{out}}
{{out}}
<pre>myDir is not empty</pre>
<pre>myDir is not empty</pre>



=={{header|PowerShell}}==
=={{header|PowerShell}}==


{{works with|PowerShell|4.0}}
{{works with|PowerShell|4.0}}
<syntaxhighlight lang="powershell">
<lang PowerShell>
$path = "C:\Users"
$path = "C:\Users"
if((Dir $path).Count -eq 0) {
if((Dir $path).Count -eq 0) {
Line 912: Line 1,114:
"$path is not empty"
"$path is not empty"
}
}
</syntaxhighlight>
</lang>
<b>Output:</b>
<b>Output:</b>
<pre>
<pre>
Line 920: Line 1,122:
=={{header|Prolog}}==
=={{header|Prolog}}==


<lang Prolog>non_empty_file('.').
<syntaxhighlight lang="prolog">non_empty_file('.').
non_empty_file('..').
non_empty_file('..').


empty_dir(Dir) :-
empty_dir(Dir) :-
directory_files(Dir, Files),
directory_files(Dir, Files),
maplist(non_empty_file, Files).</lang>
maplist(non_empty_file, Files).</syntaxhighlight>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang purebasic>Procedure isDirEmpty(path$)
<syntaxhighlight lang="purebasic">Procedure isDirEmpty(path$)
If Right(path$, 1) <> "\": path$ + "\": EndIf
If Right(path$, 1) <> "\": path$ + "\": EndIf
Protected dirID = ExamineDirectory(#PB_Any, path$, "*.*")
Protected dirID = ExamineDirectory(#PB_Any, path$, "*.*")
Line 956: Line 1,158:
EndIf
EndIf
MessageRequester("Empty directory test", #DQUOTE$ + path$ + #DQUOTE$ + result$)
MessageRequester("Empty directory test", #DQUOTE$ + path$ + #DQUOTE$ + result$)
EndIf </lang>
EndIf </syntaxhighlight>
{{out}} when selecting directories "L:\vv\6\" and "L:\vv\" :
{{out}} when selecting directories "L:\vv\6\" and "L:\vv\" :
<pre>"L:\vv\6\" is empty.
<pre>"L:\vv\6\" is empty.
Line 964: Line 1,166:
=={{header|Python}}==
=={{header|Python}}==
{{works with|Python|2.x}}
{{works with|Python|2.x}}
<lang python>import os;
<syntaxhighlight lang="python">import os;
if os.listdir(raw_input("directory")):
if os.listdir(raw_input("directory")):
print "not empty"
print "not empty"
else:
else:
print "empty"
print "empty"
</syntaxhighlight>
</lang>

=={{header|R}}==
<syntaxhighlight lang="r">
is_dir_empty <- function(path){
if(length(list.files(path)) == 0)
print("This folder is empty")
}
is_dir_empty(path)
</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==


<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket
(empty? (directory-list "some-directory"))
(empty? (directory-list "some-directory"))
</syntaxhighlight>
</lang>

=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line>sub dir-is-empty ($d) { not dir $d }</syntaxhighlight>
The <tt>dir</tt> function returns a lazy list of filenames, excluding "<tt>.</tt>" and "<tt>..</tt>" automatically. Any boolean context (in this case the <tt>not</tt> 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.


=={{header|REXX}}==
=={{header|REXX}}==
{{works with|Regina}}
{{works with|Regina}}
The following program was tested in a DOS window under Windows/XP and should work for all Microsoft Windows.
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.*/
<syntaxhighlight 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.*/
parse arg xdir; if xdir='' then xdir='\someDir' /*Any DIR? Use default.*/
@.=0 /*default in case ADDRESS fails. */
@.=0 /*default in case ADDRESS fails. */
Line 994: Line 1,211:
if #==0 then #=' no ' /*use a word, ¬zero.*/
if #==0 then #=' no ' /*use a word, ¬zero.*/
say center('directory ' xdir " has " # ' entries.',79,'─')
say center('directory ' xdir " has " # ' entries.',79,'─')
exit @.0+rc /*stick a fork in it, we're done.*/</lang>
exit @.0+rc /*stick a fork in it, we're done.*/</syntaxhighlight>
{{out}} when the following input was used: &nbsp; <tt> temp </tt>
{{out}} when the following input was used: &nbsp; <tt> temp </tt>
<pre>
<pre>
Line 1,005: Line 1,222:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
myList = dir("C:\Ring\bin")
myList = dir("C:\Ring\bin")
if len(myList) > 0 see "C:\Ring\bin is not empty" + nl
if len(myList) > 0 see "C:\Ring\bin is not empty" + nl
else see "C:\Ring\bin is empty" + nl ok
else see "C:\Ring\bin is empty" + nl ok
</syntaxhighlight>
</lang>

=={{header|RPL}}==
≪ 1 OVER SIZE '''FOR''' j
DUP j GET EVAL
'''NEXT''' DROP
VARS SIZE NOT
≫ ''''MTDIR'''' STO
{{in}}
<pre>
{ HOME °RZTA °TEST } MTDIR
</pre>
{{out}}
<pre>
1: 0
</pre>


=={{header|Ruby}}==
=={{header|Ruby}}==
Raises a SystemCallError if the named directory doesn’t exist.
Raises a SystemCallError if the named directory doesn’t exist.
<lang ruby>Dir.entries("testdir").empty? </lang>
<syntaxhighlight lang="ruby">Dir.entries("testdir").empty? </syntaxhighlight>


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>files #f, DefaultDir$ + "\*.*" ' open some directory.
<syntaxhighlight lang="runbasic">files #f, DefaultDir$ + "\*.*" ' open some directory.
print "hasanswer: ";#f HASANSWER() ' if it has an answer it is not MT
print "hasanswer: ";#f HASANSWER() ' if it has an answer it is not MT
print "rowcount: ";#f ROWCOUNT() ' if not MT, how many files?</lang>
print "rowcount: ";#f ROWCOUNT() ' if not MT, how many files?</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>use std::fs::read_dir;
<syntaxhighlight lang="rust">use std::fs::read_dir;
use std::error::Error;
use std::error::Error;


Line 1,041: Line 1,273:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>import java.io.File
<syntaxhighlight lang="scala">import java.io.File


def isDirEmpty(file:File) : Boolean =
def isDirEmpty(file:File) : Boolean =
return file.exists && file.isDirectory && file.list.isEmpty</lang>
return file.exists && file.isDirectory && file.list.isEmpty</syntaxhighlight>


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "osfiles.s7i";
include "osfiles.s7i";


Line 1,059: Line 1,291:
begin
begin
writeln(dirEmpty("somedir"));
writeln(dirEmpty("somedir"));
end func;</lang>
end func;</syntaxhighlight>

=={{header|SenseTalk}}==
The filesAndFolders function returns an empty list if a directory is empty (and does not return '.' or '..').
<syntaxhighlight lang="sensetalk">put the temporary folder & "NewFolder" into newFolderPath
make folder newFolderPath -- create a new empty directory

if the filesAndFolders in newFolderPath is empty then
put "Directory " & newFolderPath & " is empty!"
else
put "Something is present in " & newFolderPath
end if
</syntaxhighlight>
{{out}}
<pre>
Directory /var/folders/dp/0nmm3z4m8xl5m3008k8db78h0000gn/T/NewFolder is empty!
</pre>


=={{header|Sidef}}==
=={{header|Sidef}}==
Built-in method:
Built-in method:
<lang ruby>Dir.new('/my/dir').is_empty; # true, false or nil</lang>
<syntaxhighlight lang="ruby">Dir.new('/my/dir').is_empty; # true, false or nil</syntaxhighlight>


User-defined function:
User-defined function:
<lang ruby>func is_empty(dir) {
<syntaxhighlight lang="ruby">func is_empty(dir) {
dir.open(\var dir_h) || return nil;
dir.open(\var dir_h) || return nil;
dir_h.each { |file|
dir_h.each { |file|
Line 1,073: Line 1,321:
};
};
return true;
return true;
};</lang>
};</syntaxhighlight>


=={{header|Standard ML}}==
=={{header|Standard ML}}==
<lang sml>fun isDirEmpty(path: string) =
<syntaxhighlight lang="sml">fun isDirEmpty(path: string) =
let
let
val dir = OS.FileSys.openDir path
val dir = OS.FileSys.openDir path
Line 1,087: Line 1,335:
| _ => false
| _ => false
)
)
end;</lang>
end;</syntaxhighlight>



=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl>proc isEmptyDir {dir} {
<syntaxhighlight lang="tcl">proc isEmptyDir {dir} {
# Get list of _all_ files in directory
# Get list of _all_ files in directory
set filenames [glob -nocomplain -tails -directory $dir * .*]
set filenames [glob -nocomplain -tails -directory $dir * .*]
# Check whether list is empty (after filtering specials)
# Check whether list is empty (after filtering specials)
expr {![llength [lsearch -all -not -regexp $filenames {^\.\.?$}]]}
expr {![llength [lsearch -all -not -regexp $filenames {^\.\.?$}]]}
}</lang>
}</syntaxhighlight>


=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
<lang bash>
<syntaxhighlight lang="bash">
#!/bin/sh
#!/bin/sh
DIR=/tmp/foo
DIR=/tmp/foo
[ `ls -a $DIR|wc -l` -gt 2 ] && echo $DIR is NOT empty || echo $DIR is empty
[ `ls -a $DIR|wc -l` -gt 2 ] && echo $DIR is NOT empty || echo $DIR is empty
</syntaxhighlight>
</lang>


=={{header|VBA}}==
=={{header|VBA}}==
<lang vb>Sub Main()
<syntaxhighlight lang="vb">Sub Main()
Debug.Print IsEmptyDirectory("C:\Temp")
Debug.Print IsEmptyDirectory("C:\Temp")
Debug.Print IsEmptyDirectory("C:\Temp\")
Debug.Print IsEmptyDirectory("C:\Temp\")
Line 1,116: Line 1,363:
D = IIf(Right(D, 1) <> Sep, D & Sep, D)
D = IIf(Right(D, 1) <> Sep, D & Sep, D)
IsEmptyDirectory = (Dir(D & "*.*") = "")
IsEmptyDirectory = (Dir(D & "*.*") = "")
End Function</lang>
End Function</syntaxhighlight>


=={{header|VBScript}}==
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
Function IsDirEmpty(path)
Function IsDirEmpty(path)
IsDirEmpty = False
IsDirEmpty = False
Line 1,132: Line 1,379:
WScript.StdOut.WriteLine IsDirEmpty("C:\Temp")
WScript.StdOut.WriteLine IsDirEmpty("C:\Temp")
WScript.StdOut.WriteLine IsDirEmpty("C:\Temp\test")
WScript.StdOut.WriteLine IsDirEmpty("C:\Temp\test")
</syntaxhighlight>
</lang>


{{Out}}
{{Out}}
Line 1,138: Line 1,385:
False
False
True
True
</pre>

=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">import os

fn main() {
println(is_empty_dir('../Check'))
}

fn is_empty_dir(name string) string {
if os.is_dir(name) == false {return 'Directory name not exist!'}
if os.is_dir(name) && os.is_dir_empty(name) == true {return 'Directory exists and is empty!'}
return 'Directory not empty!'
}
</syntaxhighlight>

=={{header|Wren}}==
<syntaxhighlight lang="wren">import "io" for Directory

var isEmptyDir = Fn.new { |path|
if (!Directory.exists(path)) Fiber.abort("Directory at '%(path)' does not exist.")
return Directory.list(path).count == 0
}

var path = "test"
var empty = isEmptyDir.call(path)
System.print("'%(path)' is %(empty ? "empty" : "not empty")")</syntaxhighlight>

{{out}}
'test' is an empty directory I made earlier.
<pre>
'test' is empty
</pre>
</pre>


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>path:="Empty"; File.isDir(path).println();
<syntaxhighlight lang="zkl">path:="Empty"; File.isDir(path).println();
File.mkdir(path); File.isDir(path).println();
File.mkdir(path); File.isDir(path).println();
File.glob(path+"/*").println(); // show contents of directory</lang>
File.glob(path+"/*").println(); // show contents of directory</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>

Latest revision as of 16:58, 28 November 2023

Task
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.

11l

I fs:list_dir(input()).empty
   print(‘empty’)
E
   print(‘not empty’)

8086 Assembly

Translation of: MS-DOS
; this routine attempts to remove the directory and returns an error code if it cannot.

mov ax,seg dirname           ;load into AX the segment where dirname is stored.
mov ds,ax                    ;load the segment register DS with the segment of dirname
mov dx,offset dirname        ;load into DX the offset of dirname
mov ah,39h                   ;0x39 is the interrupt code for remove directory
int 21h                      ;sets carry if error is encountered. error code will be in AX. 
                             ;If carry is clear the remove was successful

jc error

mov ah,4Ch	;return function
mov al,0	;required return code
int 21h         ;return to DOS

error:          ;put your error handler here

mov ah,4Ch	;return function
mov al,0	;required return code
int 21h         ;return to DOS


dirname    db "GAMES",0

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;
Output:
Not empty
Is empty.
Not a Directory.
Does not exist.

ALGOL 68

Works with: ALGOL 68G version Any - tested with release 2.8.3.win32

This uses the "argc", "argv", "file is directory" and "get directory" procedures specific to Algol 68 G.
Note the Algol 68 G interpreter processes the command line parameters before "-" so this example expects the directory names to follow "-".

# returns TRUE if the specified directory is empty, FALSE if it doesn't exist or is non-empty #
PROC is empty directory = ( STRING directory )BOOL:
     IF NOT file is directory( directory )
     THEN
         # directory doesn't exist #
         FALSE
     ELSE
         # directory is empty if it contains no files or just "." and possibly ".." #
         []STRING files   = get directory( directory );
         BOOL     result := FALSE;
         FOR f FROM LWB files TO UPB files
         WHILE result := files[ f ] = "." OR files[ f ] = ".."
         DO
             SKIP
         OD;
         result
     FI # is empty directory # ;

# test the is empty directory procedure #
# show whether the directories specified on the command line ( following "-" ) are empty or not #
BOOL directory name parameter := FALSE;
FOR i TO argc DO
    IF argv( i ) = "-"
    THEN
        # marker to indicate directory names follow #
        directory name parameter := TRUE
    ELIF directory name parameter
    THEN
        # have a directory name - report whether it is emty or not #
        print( ( argv( i ), " is ", IF is empty directory( argv( i ) ) THEN "empty" ELSE "not empty" FI, newline ) )
    FI
OD
Output:
H:\algol\rosetta>a68g emptyDirectory.a68 - . /temp \zz
. is not empty
/temp is not empty
\zz is empty

Arturo

emptyDir?: function [folder]-> empty? list folder

print emptyDir? "."
Output:
false

AutoHotkey

MsgBox % isDir_empty(A_ScriptDir)?"true":"false"

isDir_empty(p) {
	Loop, %p%\* , 1
		return 0
	return 1
}
Output:
false

AWK

# syntax: GAWK -f EMPTY_DIRECTORY.AWK
BEGIN {
    n = split("C:\\TEMP3,C:\\NOTHERE,C:\\AWK\\FILENAME,C:\\WINDOWS",arr,",")
    for (i=1; i<=n; i++) {
      printf("'%s' %s\n",arr[i],is_dir(arr[i]))
    }
    exit(0)
}
function is_dir(path,  cmd,dots,entries,msg,rec,valid_dir) {
    cmd = sprintf("DIR %s 2>NUL",path) # MS-Windows
    while ((cmd | getline rec) > 0) {
      if (rec ~ /[0-9]:[0-5][0-9]/) {
        if (rec ~ / (\.|\.\.)$/) { # . or ..
          dots++
          continue
        }
        entries++
      }
      if (rec ~ / Dir\(s\) .* bytes free$/) {
        valid_dir = 1
      }
    }
    close(cmd)
    if (valid_dir == 0) {
      msg = "does not exist"
    }
    else if (valid_dir == 1 && entries == 0) {
      msg = "is an empty directory"
    }
    else if (dots == 0 && entries == 1) {
      msg = "is a file"
    }
    else {
      msg = sprintf("is a directory with %d entries",entries)
    }
    return(msg)
}
Output:
'C:\TEMP3' is an empty directory
'C:\NOTHERE' does not exist
'C:\AWK\FILENAME' is a file
'C:\WINDOWS' is a directory with 98 entries

BASIC

BaCon

FUNCTION check$(dir$)

    IF FILEEXISTS(dir$) THEN
        RETURN IIF$(LEN(WALK$(dir$, 127, ".+", FALSE)), " is NOT empty.", " is empty." )
    ELSE
        RETURN " doesn't exist."
    ENDIF

ENDFUNCTION

dir$ = "bla"
PRINT "Directory '", dir$, "'", check$(dir$)

dir$ = "/mnt"
PRINT "Directory '", dir$, "'", check$(dir$)

dir$ = "."
PRINT "Directory '", dir$, "'", check$(dir$)
Output:
Directory 'bla' doesn't exist.
Directory '/mnt' is empty.
Directory '.' is NOT empty.

Batch File

This demo verifies first if the directory exists. This script returns errorlevel code:

  • 0 - input directory is empty.
  • 1 - input directory is NOT empty.
  • 2 - input directory does not exist.
  • 3 - input not found.
@echo off
if "%~1"=="" exit /b 3
set "samp_path=%~1"
set "tst_var="

	%== Store the current directory of the CMD ==%
for /f %%T in ('cd') do set curr_dir=%%T

	%== Go to the samp_path ==%
cd %samp_path% 2>nul ||goto :folder_not_found

	%== The current directory is now samp_path ==%
	%== Scan what is inside samp_path ==%	
for /f "usebackq delims=" %%D in (
	`dir /b 2^>nul ^& dir /b /ah 2^>nul`
) do set "tst_var=1"

if "%tst_var%"=="1" (
	echo "%samp_path%" is NOT empty.
	cd %curr_dir%
	exit /b 1
) else (
	echo "%samp_path%" is empty.
	cd %curr_dir%
	exit /b 0
)

:folder_not_found
echo Folder not found.
exit /b 2
Sample Session:

(Saved the Batch File as IsEmpty.Bat in C:\)

C:\>IsEmpty

C:\>echo %errorlevel%
3

C:\>IsEmpty "C:\Sample"
Folder not found.

C:\>md Sample

C:\>IsEmpty "C:\Sample"
"C:\Sample" is empty.

C:\>cd Sample

C:\Sample>echo 0123456789 >>digits.txt

C:\Sample>dir /b
digits.txt

C:\Sample>cd..

C:\>IsEmpty "C:\Sample"
"C:\Sample" is NOT empty.

C:\>

BBC BASIC

      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)

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;
}

Running it:

% mkdir stuff; ./a.out /usr/ ./stuff /etc/passwd
/usr/: not empty
./stuff: empty
/etc/passwd: Not a directory

C#

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 );
    }
}

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

C++

Library: Boost
#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";
    }
}

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 ".."

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

Common Lisp

Will also return T if path doesn't exist.

(defun empty-directory-p (path)
  (and (null (directory (concatenate 'string path "/*")))
       (null (directory (concatenate 'string path "/*/")))))

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;
}
somedir is empty: false

Delphi

Translation of: C#
program Empty_directory;

{$APPTYPE CONSOLE}

uses
  System.SysUtils,
  System.IOUtils;

function IsDirectoryEmpty(dir: string): Boolean;
var
  count: Integer;
begin
  count := Length(TDirectory.GetFiles(dir)) + Length(TDirectory.GetDirectories(dir));
  Result := count = 0;
end;

var
  i: Integer;

const
  CHECK: array[Boolean] of string = (' is not', ' is');

begin
  if ParamCount > 0 then
    for i := 1 to ParamCount do
      Writeln(ParamStr(i), CHECK[IsDirectoryEmpty(ParamStr(i))], ' empty');
  Readln;
end.
Output:

The same of c#.

Elixir

path = hd(System.argv)
IO.puts File.dir?(path) and Enum.empty?( File.ls!(path) )

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#

open System.IO
let isEmptyDirectory x = (Directory.GetFiles x).Length = 0 && (Directory.GetDirectories x).Length = 0

Factor

USE: io.directories
: empty-directory? ( path -- ? ) directory-entries empty? ;

FreeBASIC

' FB 1.05.0 Win64

#Include "dir.bi"

Function IsDirEmpty(dirPath As String) As Boolean
  Err = 0
  ' check dirPath is a valid directory
  Dim As String fileName = Dir(dirPath, fbDirectory)
  If Len(fileName) = 0 Then
    Err = 1000  ' dirPath is not a valid path
    Return False
  End If
  ' now check if there are any files/subdirectories in it other than . and ..
  Dim fileSpec As String = dirPath + "\*.*"
  Const attribMask = fbNormal Or fbHidden Or fbSystem Or fbDirectory
  Dim outAttrib As UInteger
  fileName = Dir(fileSpec, attribMask, outAttrib)  ' get first file
  Do
    If fileName <> ".." AndAlso fileName <> "." Then
      If Len(fileName) = 0 Then Return True
      Exit Do
    End If
    fileName = Dir  ' get next file
  Loop
  Return False
End Function

Dim outAttrib As UInteger
Dim dirPath As String = "c:\freebasic\docs"  ' known to be empty
Dim empty As Boolean = IsDirEmpty(dirPath)
Dim e As Long = Err
If e = 1000 Then
  Print "'"; dirPath; "' is not a valid directory"
  End
End If
If empty Then
  Print "'"; dirPath; "' is empty"
Else
  Print "'"; dirPath; "' is not empty"
End If
Print
Print "Press any key to quit"
Sleep
Output:
'c:\freebasic\docs' is empty

FutureBasic

include "NSLog.incl"

local fn DirectoryContents( url as CFURLRef ) as CFArrayRef
  CFArrayRef contents = fn FileManagerContentsOfDirectoryAtURL( url, NULL, NSDirectoryEnumerationSkipsHiddenFiles )
  if ( contents == NULL )
    NSLog(@"Unable to get contents of directory \"%@\".",fn URLLastPathComponent(url))
  end if
end fn = fn ArrayValueForKey( contents, @"lastPathComponent" )

void local fn DoIt
  CFURLRef   dirURL, fileURL
  CFArrayRef contents
  
  dirURL = fn URLFileURLWithPath( fn StringByExpandingTildeInPath( @"~/Desktop/docs" ) )
  if ( fn FileManagerCreateDirectoryAtURL( dirURL, YES, NULL ) )
    contents = fn DirectoryContents( dirURL )
    if ( contents )
      NSLog(@"Directory \"docs\" \b")
      if ( len(contents) )
        NSLog(@"contents:\n%@",contents)
      else
        NSLog(@"is empty.")
      end if
      
      NSLog(@"")
      
      fileURL = fn URLFileURLWithPath( fn StringByExpandingTildeInPath( @"~/Desktop/docs/output.txt" ) )
      if (fn FileManagerCreateFileAtURL( fileURL, NULL, NULL ) )
        contents = fn DirectoryContents( dirURL )
        NSLog(@"Directory \"docs\" \b")
        if ( len(contents) )
          NSLog(@"contents:\n%@",contents)
        else
          NSLog(@"is empty.")
        end if
      end if
    end if
  end if
  
end fn

fn DoIt

HandleEvents
Output:
Directory "docs" is empty.

Directory "docs" contents:
(
    "output.txt"
)

Gambas

Public Sub Main()
Dim sFolder As String = User.home &/ "Rosetta"
Dim sDir As String[] = Dir(sFolder)
Dim sTemp As String
Dim sOutput As String = sfolder & " is NOT empty"

Try sTemp = sDir[0]
If Error Then sOutput = sfolder & " is empty"

Print sOutput

End

Output:

/home/charlie/Rosetta is empty

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
}

Groovy

Solution:

def isDirEmpty = { dirName ->
    def dir = new File(dirName)
    dir.exists() && dir.directory && (dir.list() as List).empty
}

Test:

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)

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

Test:

$ mkdir 1
$ ./isempty 1
Directory is empty
$ ./isempty /usr/
Directory is not empty


Icon and Unicon

This example uses Unicon extensions. The 'empty' sub-directory was manually setup for this test.

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
Output:
. is not empty
./empty is empty

J

require 'dir'
empty_dir=: 0 = '/*' #@dir@,~ ]

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:

$ mkdir /tmp/a
$ touch /tmp/a/...
$ mkdir /tmp/b
$ mkdir /tmp/c
$ mkdir /tmp/c/d

Then, testing these directories, in J:

   empty_dir 'c:/cygwin/tmp/a'
0
   empty_dir 'c:/cygwin/tmp/b'
1
   empty_dir 'c:/cygwin/tmp/c'
0

Java

Works with: Java version 7+

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.

import java.nio.file.Paths;
//... other class code here
public static boolean isEmptyDir(String dirName){
    return Paths.get(dirName).toFile().listFiles().length == 0;
}

JavaScript

The ECMAScript standard itself defines no IO interface – the following example makes use of the Node.js file IO library.

Works with: Node.js
// Node.js v14.15.4
const { readdirSync } = require("fs");
const emptydir = (path) => readdirSync(path).length == 0;

// tests, run like node emptydir.js [directories]
for (let i = 2; i < process.argv.length; i ++) {
  let dir = process.argv[i];
  console.log(`${dir}: ${emptydir(dir) ? "" : "not "}empty`)
}

Julia

# v0.6.0
isemptydir(dir::AbstractString) = isempty(readdir(dir))

@show isemptydir(".")
@show isemptydir("/home")
Output:
isemptydir(".") = false
isemptydir("/home") = false

Kotlin

// version 1.1.4

import java.io.File

fun main(args: Array<String>) {
    val dirPath = "docs" // or whatever
    val isEmpty = (File(dirPath).list().isEmpty())
    println("$dirPath is ${if (isEmpty) "empty" else "not empty"}")
}

Lasso

dir('has_content') -> isEmpty
'<br />'
dir('no_content') -> isEmpty
Output:
false
true

Liberty BASIC

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

Lingo

on isDirEmpty (dir)
  return getNthFileNameInFolder(dir, 1) = EMPTY
end

Lua

Pure Lua function based on snipplet from Stack Overflow[1].

function scandir(directory)
	local i, t, popen = 0, {}, io.popen
	local pfile = popen('ls -a "'..directory..'"')
	for filename in pfile:lines() do
		if filename ~= '.' and filename ~= '..' then
			i = i + 1
			t[i] = filename
		end
	end
	pfile:close()
	return t
end

function isemptydir(directory)
	return #scandir(directory) == 0
end

Using lfs[2] library.

function isemptydir(directory,nospecial)
	for filename in require('lfs').dir(directory) do
		if filename ~= '.' and filename ~= '..' then
			return false
		end
	end
	return true
end

Maple

emptydirectory := proc (dir) 
is(listdir(dir) = [".", ".."]); 
end proc;

Mathematica / Wolfram Language

EmptyDirectoryQ[x_] := (SetDirectory[x]; If[FileNames[] == {}, True, False])

Example use:
EmptyDirectoryQ["C:\\Program Files\\Wolfram Research\\Mathematica\\9"]
->True

MATLAB / Octave

  function x = isEmptyDirectory(p)
    if isdir(p)		
      f = dir(p)
      x = length(f)>2;
    else 
      error('Error: %s is not a directory');     
    end; 
  end;

min

Works with: min version 0.19.3
(ls bool not) :empty-dir?

MS-DOS

Since you cannot remove a directory that isn't empty, one way to check is to attempt to remove it.

C:\>rd GAMES
Unable to remove: GAMES.

C:\>

Nanoquery

def isempty(dirname)
        return len(new(Nanoquery.IO.File).listDir(dirname)) = 0
end

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");
            }
        }
    }
}

NewLISP

(define (empty-dir? path-to-check)
	(empty? (clean (lambda (x) (or (= "." x) (= ".." x))) (directory path-to-check)))
)

Nim

import os, rdstdin

var empty = true
for f in walkDir(readLineFromStdin "directory: "):
  empty = false
  break
echo empty

Alternatively:

import os, sequtils

proc isEmptyDir(dir: string): bool =
  toSeq(walkdir dir).len == 0

echo isEmptyDir("/tmp")  # false - there is always something in "/tmp"
echo isEmptyDir("/temp") # true  - "/temp" does not exist

Objeck

function : IsEmptyDirectory(dir : String) ~ Bool {
  return Directory->List(dir)->Size() = 0;
}

OCaml

let is_dir_empty d =
  Sys.readdir d = [| |]

ooRexx

Call test 'D:\nodir'        /* no such directory      */
Call test 'D:\edir'         /* an empty directory     */
Call test 'D:\somedir'      /* directory with 2 files */
Call test 'D:\somedir','S'  /* directory with 3 files */
Exit
test: Parse Arg fd,nest
If SysIsFileDirectory(fd)=0 Then
  Say 'Directory' fd 'not found'
Else Do
  ret=SysFileTree(fd'\*.*','X', 'F'nest)
  If x.0=0 Then
    say 'Directory' fd 'is empty'
  Else Do
    If nest='' Then
      say 'Directory' fd 'contains' x.0 'files'
    Else
      say 'Directory' fd 'contains' x.0 'files (some nested)'
    End
  End
Return
Output:
Directory D:\nodir not found
Directory D:\edir is empty
Directory D:\somedir contains 2 files
Directory D:\somedir contains 3 files (some nested)

PARI/GP

Define a function chkdir(<path>) that returns count of entries in a directory (without . and .. ):

chkdir(d)=extern(concat(["[ -d '",d,"' ]&&ls -A '",d,"'|wc -l||echo -1"]))

On error chkdir(...) returns -1 else count of entries. If chkdir() == 0 then directory is empty. So define an additional function:

dir_is_empty(d)=!chkdir(d)

Output:

chkdir("/tmp"): 52

dir_is_empty("/tmp"): 0

Pascal

Works with: GNU Pascal

Pascal does not know the notion of directories. Therefore it is not possible to determine whether a directory is empty.

However, GNU Pascal provides certain extensions to Extended Pascal (ISO 10206) so it is possible nonetheless. Note, the following solution works only on strictly hierarchical file systems.

program emptyDirectory(input, output);

type
	path = string(1024);

{
	\brief determines whether a (hierarchial FS) directory is empty
	
	\param accessVia a possible route to access a directory
	\return whether \param accessVia is an empty directory
}
function isEmptyDirectory(protected accessVia: path): Boolean;
var
	{ NB: `file` data types without a domain type are non-standard }
	directory: bindable file;
	FD: bindingType;
begin
	{ initialize variables }
	unbind(directory);
	FD := binding(directory);
	
	FD.name := accessVia;
	{ binding to directories is usually not possible }
	FD.force := true;
	
	{ the actual test }
	bind(directory, FD);
	FD := binding(directory);
	unbind(directory);
	
	isEmptyDirectory := FD.bound and FD.directory and (FD.links <= 2)
end;

{ === MAIN ============================================================= }
var
	s: path;
begin
	readLn(s);
	writeLn(isEmptyDirectory(s))
end.

Note, symbolic links’ targets are resolved, so accessVia could in fact be a symbolic link to an empty directory.

Perl

Simple version

sub dir_is_empty {!<$_[0]/*>}

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

use IO::Dir;
sub dir_is_empty { !grep !/^\.{1,2}\z/, IO::Dir->new(@_)->read }

Phix

without js -- file i/o
procedure test(string filename)
    string msg
    switch get_file_type(filename) do
        case FILETYPE_UNDEFINED: msg = "is UNDEFINED"
        case FILETYPE_NOT_FOUND: msg = "is NOT_FOUND"
        case FILETYPE_FILE:      msg = "is a FILE"
        case FILETYPE_DIRECTORY:
            integer count = length(filter(vslice(dir(filename),D_NAME),"out",{".",".."}))
            msg = iff(count=0?"is an empty directory"
                             :sprintf("is a directory containing %d files",{count}))
    end switch
    printf(1,"%s %s\n",{filename,msg})
end procedure
 
constant tests = {"C:\\xx","C:\\not_there","C:\\Program Files (x86)\\Phix\\p.exe","C:\\Windows"}
for i=1 to length(tests) do
    test(tests[i])
end for
Output:
C:\xx is an empty directory
C:\not_there is NOT_FOUND
C:\Program Files (x86)\Phix\p.exe is a FILE
C:\Windows is a directory containing 110 files

PHP

Any improvements welcome but here is a starting point for 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';
}

PicoLisp

(prinl "myDir is" (and (dir "myDir") " not") " empty")
Output:
myDir is not empty

PowerShell

Works with: PowerShell version 4.0
$path = "C:\Users"
if((Dir $path).Count -eq 0) {
    "$path is empty"
} else {
    "$path is not empty"
}

Output:

C:\Users is not empty

Prolog

non_empty_file('.').
non_empty_file('..').

empty_dir(Dir) :-
	directory_files(Dir, Files),
	maplist(non_empty_file, Files).

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
Output:

when selecting directories "L

\vv\6\" and "L:\vv\" :
"L:\vv\6\" is empty.

"L:\vv\" is not empty.

Python

Works with: Python version 2.x
import os;
if os.listdir(raw_input("directory")):
    print "not empty"
else:
    print "empty"

R

  is_dir_empty <- function(path){
    if(length(list.files(path)) == 0)
      print("This folder is empty")
  }
  
  is_dir_empty(path)

Racket

#lang racket
(empty? (directory-list "some-directory"))

Raku

(formerly Perl 6)

sub dir-is-empty ($d) { not dir $d }

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.

REXX

Works with: Regina

The following program was tested in a DOS window under Windows/XP and should work for all Microsoft Windows.

/*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.*/
Output:

when the following input was used

  temp
──────────────────────directory  temp  has  10  entries.───────────────────────
Output:

when the following input was used

  \someDir
───────────────────directory  \someDir  has    no   entries.───────────────────

Ring

myList = dir("C:\Ring\bin")
if len(myList) > 0 see "C:\Ring\bin is not empty" + nl
else see "C:\Ring\bin is empty" + nl ok

RPL

≪ 1 OVER SIZE FOR j 
      DUP j GET EVAL 
   NEXT DROP 
   VARS SIZE NOT
≫ 'MTDIR' STO
Input:
{ HOME °RZTA °TEST } MTDIR
Output:
1: 0

Ruby

Raises a SystemCallError if the named directory doesn’t exist.

Dir.entries("testdir").empty?

Run BASIC

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?

Rust

use std::fs::read_dir;
use std::error::Error;

fn main() {
    for path in std::env::args().skip(1) { // iterate over the arguments, skipping the first (which is the executable)
        match read_dir(path.as_str()) { // try to read the directory specified
            Ok(contents) => {
                let len = contents.collect::<Vec<_>>().len(); // calculate the amount of items in the directory
                if len == 0 {
                    println!("{} is empty", path);
                } else {
                    println!("{} is not empty", path);
                }
            },
            Err(e) => { // If the attempt failed, print the corresponding error msg
                println!("Failed to read directory \"{}\": {}", path, e.description());
            }
        }
    }
}

Scala

import java.io.File

def isDirEmpty(file:File) : Boolean =
   return file.exists && file.isDirectory && file.list.isEmpty

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;

SenseTalk

The filesAndFolders function returns an empty list if a directory is empty (and does not return '.' or '..').

put the temporary folder & "NewFolder" into newFolderPath
make folder newFolderPath -- create a new empty directory

if the filesAndFolders in newFolderPath is empty then
	put "Directory " & newFolderPath & " is empty!"
else
	put "Something is present in " & newFolderPath
end if
Output:
Directory /var/folders/dp/0nmm3z4m8xl5m3008k8db78h0000gn/T/NewFolder is empty!

Sidef

Built-in method:

Dir.new('/my/dir').is_empty;    # true, false or nil

User-defined function:

func is_empty(dir) {
    dir.open(\var dir_h) || return nil;
    dir_h.each { |file|
        file ~~ ['.', '..'] && next;
        return false;
    };
    return true;
};

Standard ML

fun isDirEmpty(path: string) = 
  let
    val dir = OS.FileSys.openDir path
    val dirEntryOpt = OS.FileSys.readDir dir
  in
    (
      OS.FileSys.closeDir(dir);
      case dirEntryOpt of 
        NONE => true
      | _    => false
    )
  end;

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 {^\.\.?$}]]}
}

UNIX Shell

#!/bin/sh
DIR=/tmp/foo
[ `ls -a $DIR|wc -l` -gt 2 ]  && echo $DIR is NOT empty || echo $DIR is empty

VBA

Sub Main()
    Debug.Print IsEmptyDirectory("C:\Temp")
    Debug.Print IsEmptyDirectory("C:\Temp\")
End Sub

Private Function IsEmptyDirectory(D As String) As Boolean
Dim Sep As String
    Sep = Application.PathSeparator
    D = IIf(Right(D, 1) <> Sep, D & Sep, D)
    IsEmptyDirectory = (Dir(D & "*.*") = "")
End Function

VBScript

Function IsDirEmpty(path)
	IsDirEmpty = False
	Set objFSO = CreateObject("Scripting.FileSystemObject")
	Set objFolder = objFSO.GetFolder(path)
	If objFolder.Files.Count = 0 And objFolder.SubFolders.Count = 0 Then
		IsDirEmpty = True
	End If
End Function

'Test
WScript.StdOut.WriteLine IsDirEmpty("C:\Temp")
WScript.StdOut.WriteLine IsDirEmpty("C:\Temp\test")
Output:
False
True

V (Vlang)

import os

fn main() {
    println(is_empty_dir('../Check'))
}

fn is_empty_dir(name string) string {
    if os.is_dir(name) == false {return 'Directory name not exist!'}
    if os.is_dir(name) && os.is_dir_empty(name) == true {return 'Directory exists and is empty!'}
    return 'Directory not empty!'
}

Wren

import "io" for Directory

var isEmptyDir = Fn.new { |path|
    if (!Directory.exists(path)) Fiber.abort("Directory at '%(path)' does not exist.")
    return Directory.list(path).count == 0
}

var path = "test"
var empty = isEmptyDir.call(path)
System.print("'%(path)' is %(empty ? "empty" : "not empty")")
Output:

'test' is an empty directory I made earlier.

'test' is empty

zkl

path:="Empty"; File.isDir(path).println();
File.mkdir(path); File.isDir(path).println();
File.glob(path+"/*").println(); // show contents of directory
Output:
False
True
L()