Empty directory: Difference between revisions

Content added Content deleted
No edit summary
m (syntax highlighting fixup automation)
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}}==
=={{header|8086 Assembly}}==
{{trans|MS-DOS}}
{{trans|MS-DOS}}


<lang asm>; this routine attempts to remove the directory and returns an error code if it cannot.
<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 ax,seg dirname ;load into AX the segment where dirname is stored.
Line 36: Line 36:




dirname db "GAMES",0</lang>
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 62: 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 73: 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 104: 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 115: Line 115:
=={{header|Arturo}}==
=={{header|Arturo}}==


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


print emptyDir? "."</lang>
print emptyDir? "."</syntaxhighlight>


{{out}}
{{out}}
Line 124: Line 124:


=={{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 130: 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 173: Line 173:
return(msg)
return(msg)
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 183: Line 183:


=={{header|BaCon}}==
=={{header|BaCon}}==
<lang bacon>FUNCTION check$(dir$)
<syntaxhighlight lang="bacon">FUNCTION check$(dir$)


IF FILEEXISTS(dir$) THEN
IF FILEEXISTS(dir$) THEN
Line 200: Line 200:


dir$ = "."
dir$ = "."
PRINT "Directory '", dir$, "'", check$(dir$)</lang>
PRINT "Directory '", dir$, "'", check$(dir$)</syntaxhighlight>


{{out}}
{{out}}
Line 213: Line 213:
*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 242: Line 242:
: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 274: Line 274:
=={{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 290: Line 290:
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 332: Line 332:


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 340: Line 340:


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


Line 359: Line 359:
}
}
}
}
</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 370: Line 370:
=={{header|C++}}==
=={{header|C++}}==
{{libheader|Boost}}
{{libheader|Boost}}
<lang cpp>
<syntaxhighlight lang="cpp">
#include <iostream>
#include <iostream>
#include <boost/filesystem.hpp>
#include <boost/filesystem.hpp>
Line 387: Line 387:
}
}
}
}
</syntaxhighlight>
</lang>


=={{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 406: Line 406:
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 429: Line 429:
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}}==
=={{header|Delphi}}==
Line 435: Line 435:
{{libheader| System.IOUtils}}
{{libheader| System.IOUtils}}
{{Trans|C#}}
{{Trans|C#}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Empty_directory;
program Empty_directory;


Line 463: Line 463:
Writeln(ParamStr(i), CHECK[IsDirectoryEmpty(ParamStr(i))], ' empty');
Writeln(ParamStr(i), CHECK[IsDirectoryEmpty(ParamStr(i))], ' empty');
Readln;
Readln;
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
The same of c#.
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 485: Line 485:


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>open System.IO
<syntaxhighlight lang="fsharp">open System.IO
let isEmptyDirectory x = (Directory.GetFiles x).Length = 0 && (Directory.GetDirectories x).Length = 0</lang>
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 535: Line 535:
Print
Print
Print "Press any key to quit"
Print "Press any key to quit"
Sleep</lang>
Sleep</syntaxhighlight>


{{out}}
{{out}}
Line 543: Line 543:


=={{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 554: Line 554:
Print sOutput
Print sOutput


End</lang>
End</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 561: Line 561:


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


import (
import (
Line 588: Line 588:
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 606: Line 606:


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 617: Line 617:
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 642: Line 642:
}
}
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 650: Line 650:
=={{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 659: Line 659:
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}}==
=={{header|JavaScript}}==
The ECMAScript standard itself defines no IO interface – the following example makes use of the Node.js file IO library.
The ECMAScript standard itself defines no IO interface – the following example makes use of the Node.js file IO library.
{{Works with|Node.js}}
{{Works with|Node.js}}
<lang javascript>// Node.js v14.15.4
<syntaxhighlight lang="javascript">// Node.js v14.15.4
const { readdirSync } = require("fs");
const { readdirSync } = require("fs");
const emptydir = (path) => readdirSync(path).length == 0;
const emptydir = (path) => readdirSync(path).length == 0;
Line 694: Line 694:
let dir = process.argv[i];
let dir = process.argv[i];
console.log(`${dir}: ${emptydir(dir) ? "" : "not "}empty`)
console.log(`${dir}: ${emptydir(dir) ? "" : "not "}empty`)
}</lang>
}</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 711: Line 711:


=={{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 719: Line 719:
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 730: Line 730:


=={{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 746: Line 746:
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 772: Line 772:
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 784: Line 784:
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 811: Line 811:
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}}==
=={{header|MS-DOS}}==


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


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


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


Line 848: Line 848:
}
}
}
}
}</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 864: Line 864:
empty = false
empty = false
break
break
echo empty</lang>
echo empty</syntaxhighlight>


Alternatively:
Alternatively:


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


proc isEmptyDir(dir: string): bool =
proc isEmptyDir(dir: string): bool =
Line 874: Line 874:


echo isEmptyDir("/tmp") # false - there is always something in "/tmp"
echo isEmptyDir("/tmp") # false - there is always something in "/tmp"
echo isEmptyDir("/temp") # true - "/temp" does not exist</lang>
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 906: Line 906:
End
End
End
End
Return</lang>
Return</syntaxhighlight>
{{out}}
{{out}}
<pre>Directory D:\nodir not found
<pre>Directory D:\nodir not found
Line 916: Line 916:


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


type
type
Line 971: Line 971:
readLn(s);
readLn(s);
writeLn(isEmptyDirectory(s))
writeLn(isEmptyDirectory(s))
end.</lang>
end.</syntaxhighlight>
Note, symbolic links’ targets are resolved, so <tt>accessVia</tt> could in fact be a symbolic link ''to'' an empty directory.
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 983: Line 983:
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|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(notonline)-->
<!--<syntaxhighlight lang="phix">(notonline)-->
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- file i/o</span>
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- file i/o</span>
<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>
<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>
Line 1,007: Line 1,007:
<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>
<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>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 1,018: Line 1,018:
=={{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 1,037: Line 1,037:
}
}


</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>
Line 1,047: Line 1,047:


{{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 1,054: Line 1,054:
"$path is not empty"
"$path is not empty"
}
}
</syntaxhighlight>
</lang>
<b>Output:</b>
<b>Output:</b>
<pre>
<pre>
Line 1,062: Line 1,062:
=={{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 1,098: Line 1,098:
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 1,106: Line 1,106:
=={{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}}==
=={{header|R}}==
<syntaxhighlight lang="r">
<lang R>
is_dir_empty <- function(path){
is_dir_empty <- function(path){
if(length(list.files(path)) == 0)
if(length(list.files(path)) == 0)
Line 1,121: Line 1,121:
is_dir_empty(path)
is_dir_empty(path)
</lang>
</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}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
<lang perl6>sub dir-is-empty ($d) { not dir $d }</lang>
<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.
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.


Line 1,138: Line 1,138:
{{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 1,151: Line 1,151:
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,162: Line 1,162:


=={{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|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,198: Line 1,198:
}
}
}
}
}</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,216: Line 1,216:
begin
begin
writeln(dirEmpty("somedir"));
writeln(dirEmpty("somedir"));
end func;</lang>
end func;</syntaxhighlight>


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


Line 1,228: Line 1,228:
put "Something is present in " & newFolderPath
put "Something is present in " & newFolderPath
end if
end if
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,236: Line 1,236:
=={{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,246: Line 1,246:
};
};
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,260: Line 1,260:
| _ => 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,288: Line 1,288:
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,304: Line 1,304:
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,313: Line 1,313:


=={{header|Vlang}}==
=={{header|Vlang}}==
<lang vlang>import os
<syntaxhighlight lang="vlang">import os


fn main() {
fn main() {
Line 1,324: Line 1,324:
return 'Directory not empty!'
return 'Directory not empty!'
}
}
</syntaxhighlight>
</lang>


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


var isEmptyDir = Fn.new { |path|
var isEmptyDir = Fn.new { |path|
Line 1,336: Line 1,336:
var path = "test"
var path = "test"
var empty = isEmptyDir.call(path)
var empty = isEmptyDir.call(path)
System.print("'%(path)' is %(empty ? "empty" : "not empty")")</lang>
System.print("'%(path)' is %(empty ? "empty" : "not empty")")</syntaxhighlight>


{{out}}
{{out}}
Line 1,345: Line 1,345:


=={{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>