Walk a directory/Non-recursively: Difference between revisions

m
(Walk a directory/Non-recursively en BASIC256)
m (→‎{{header|Wren}}: Minor tidy)
 
(11 intermediate revisions by 10 users not shown)
Line 19:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">L(filename) fs:list_dir(‘/foo/bar’)
I filename.ends_with(‘.mp3’)
print(filename)</langsyntaxhighlight>
 
=={{header|68000 Assembly}}==
Non-recursive directory walk in Motorola 68000 assembly language under AmigaOs 2.04+ by Thorham. Uses regular Amiga dos pattern matching.
<langsyntaxhighlight lang="68000devpac">;
; Non-recursive directory walk for Motorola 68000 under AmigaOs 2.04+ by Thorham
;
Line 203:
 
patternParsed
dcb.b sizeof_patternString*2+2</langsyntaxhighlight>
 
=={{header|8080 Assembly}}==
Line 211:
the filename, the extension, and an optional drive letter.
 
<syntaxhighlight lang="text">exit: equ 0 ; CP/M syscall to exit
puts: equ 9 ; CP/M syscall to print a string
sfirst: equ 17 ; 'Find First' CP/M syscall
Line 254:
ret
emsg: db 'Not Found$'
fname: db 'XXXXXXXX.XXX',13,10,'$' ; Filename placeholder</langsyntaxhighlight>
 
{{out}}
Line 285:
 
=={{header|8th}}==
<langsyntaxhighlight lang="forth">
"*.c" f:glob \ puts an array of strings with the file names on the top of the stack
</syntaxhighlight>
</lang>
 
=={{header|Action!}}==
The attached result has been obtained under DOS 2.5.
<syntaxhighlight lang="action!">PROC GetFileName(CHAR ARRAY line,fname)
BYTE i,len
 
len=0
i=3
FOR i=3 TO 10
DO
IF line(i)=32 THEN EXIT FI
len==+1
fname(len)=line(i)
OD
len==+1
fname(len)='.
FOR i=11 TO 13
DO
IF line(i)=32 THEN EXIT FI
len==+1
fname(len)=line(i)
OD
fname(0)=len
RETURN
 
PROC Dir(CHAR ARRAY filter)
CHAR ARRAY line(255),fname(255)
BYTE dev=[1]
 
PrintE(filter)
Close(dev)
Open(dev,filter,6)
DO
InputSD(dev,line)
IF line(0)=0 OR line(0)>0 AND line(1)#32 THEN
EXIT
FI
GetFileName(line,fname)
Put(32) PrintE(fname)
OD
Close(dev)
PutE()
RETURN
 
PROC Main()
Dir("D:*.*")
Dir("H1:X*.*")
Dir("H1:?????.ACT")
Dir("H1:??F*.*")
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Walk_a_directory_non-recursively.png Screenshot from Atari 8-bit computer]
<pre>
D:*.*
DOS.SYS
DUP.SYS
INPUT.TXT
 
H1:X*.*
XIAOL_24.ACT
XML_O_CU.ACT
 
H1:?????.ACT
AB_3D.ACT
BREAK.ACT
CUSIP.ACT
SIEVE.ACT
SLEEP.ACT
WHILE.ACT
 
H1:??F*.*
HOFST_34.ACT
INFINITE.ACT
UTF8__P2.ACT
</pre>
 
=={{header|Ada}}==
{{works with|GCC|4.12}}
<langsyntaxhighlight lang="ada">with Ada.Directories; use Ada.Directories;
with Ada.Text_IO; use Ada.Text_IO;
 
Line 309 ⟶ 384:
 
End_Search (Search);
end Walk_Directory;</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 315 ⟶ 390:
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386 - uses non-standard library routines ''get directory'' and'' grep in string''.}}
<!-- {{does not work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386 - ''get directory'' and'' grep in string'' not available in any library ... yet}} -->
<langsyntaxhighlight lang="algol68">INT match=0, no match=1, out of memory error=2, other error=3;
 
[]STRING directory = get directory(".");
Line 323 ⟶ 398:
print((file, new line))
FI
OD</langsyntaxhighlight>
{{out|Sample output}}
<pre>
Line 339 ⟶ 414:
AppleScript itself has limited built-in file system access. Typically, the Mac OS Finder is used to gather such information.
To list all file/folders in the root directory:
<langsyntaxhighlight AppleScriptlang="applescript">tell application "Finder" to return name of every item in (startup disk)
--> EXAMPLE RESULT: {"Applications", "Developer", "Library", "System", "Users"}</langsyntaxhighlight>
To list all pdf files in user's home directory:
<langsyntaxhighlight AppleScriptlang="applescript">tell application "Finder" to return name of every item in (path to documents folder from user domain) whose name ends with "pdf"
--> EXAMPLE RESULT: {"About Stacks.pdf", "Test.pdf"}</langsyntaxhighlight>
The key clause is the <code>whose</code> modifier keyword. The Finder can interpret many variations, including such terms as <code>whose name begins with</code>, <code>whose name contains</code>, etc. As well as boolean combinations:
<langsyntaxhighlight AppleScriptlang="applescript">tell application "Finder" to return name of every item in (path to documents folder from user domain) whose name does not contain "about" and name ends with "pdf"
--> RETURNS: {"Test.pdf"}</langsyntaxhighlight>
The Finder also supports the <code>entire contents</code> modifier keyword, which effectively performs a recursive directory scan without recursion.
<langsyntaxhighlight AppleScriptlang="applescript">tell application "Finder" to return name of every item in entire contents of (path to documents folder from user domain) whose name ends with "pdf"</langsyntaxhighlight>
----
Nowadays, it's more usual to use macOS's System Events application for this kind of task as it's very much faster than the Finder, especially with 'whose' filters. However, its results, unlike the Finder's, aren't sorted by the items' names and it includes results for hidden items too if these match the criteria.
 
<langsyntaxhighlight lang="applescript">tell application "System Events" to return name of every item in documents folder whose name extension is "pdf"
--> EXAMPLE RESULT: {"ShellScripting.pdf", "RFC 4180 (CSV spec).pdf", "About Stacks.pdf", "AppleScriptLanguageGuide.pdf", "robinson_jeffers_2004_9.pdf", "DiskWarrior Manual.pdf", "RFC 2445 (iCalendar spec).pdf", "Artistic Orchestration.pdf"}</langsyntaxhighlight>
 
Intermediate in speed between the Finder and System Events are shell scripts, which are handy if you're more comfortable with shell scripts than with AppleScript.
 
<langsyntaxhighlight lang="applescript">set docsFolderPath to POSIX path of (path to documents folder)
-- By default, "ls" returns file names sorted by character code, so save the sorting until the end and do it case-insensitively.
set shellCommandText to "ls -f " & quoted form of docsFolderPath & " | grep -i '\\.pdf$' | sort -f"
return paragraphs of (do shell script shellCommandText)
--> EXAMPLE RESULT: {"About Stacks.pdf", "AppleScriptLanguageGuide.pdf", "Artistic Orchestration.pdf", "DiskWarrior Manual.pdf", "RFC 2445 (iCalendar spec).pdf", "RFC 4180 (CSV spec).pdf", "robinson_jeffers_2004_9.pdf", "ShellScripting.pdf"}</langsyntaxhighlight>
 
Best of all for speed and sorting, although requiring somewhat more code, are the Foundation methods available through AppleScriptObjC.
 
<langsyntaxhighlight lang="applescript">use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
use scripting additions
Line 383 ⟶ 458:
-- Return the result as an AppleScript list of text.
return pdfNames as list
--> EXAMPLE RESULT: {"About Stacks.pdf", "AppleScriptLanguageGuide.pdf", "Artistic Orchestration.pdf", "DiskWarrior Manual.pdf", "RFC 2445 (iCalendar spec).pdf", "RFC 4180 (CSV spec).pdf", "robinson_jeffers_2004_9.pdf", "ShellScripting.pdf"}</langsyntaxhighlight>
 
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">; list all files at current path
print list "."
 
Line 399 ⟶ 474:
; just select the files that contain "test"
select list "some/path"
=> [in? "test"]</langsyntaxhighlight>
 
=={{header|AutoHotkey}}==
Display all INI files in Windows directory.
<langsyntaxhighlight lang="autohotkey">Loop, %A_WinDir%\*.ini
out .= A_LoopFileName "`n"
MsgBox,% out</langsyntaxhighlight>
 
=={{header|BaCon}}==
This code will print all files in the current directory ".", separated by a newline symbol:
<langsyntaxhighlight lang="qbasic">PRINT WALK$(".", 1, ".+", FALSE, NL$)</langsyntaxhighlight>
 
=={{header|BASIC}}==
Line 416 ⟶ 491:
DOS wildcards are rather underpowered when compared to... well... anything else.
{{works with|FreeBASIC}}
<langsyntaxhighlight lang="qbasic">DECLARE SUB show (pattern AS STRING)
 
show "*.*"
Line 427 ⟶ 502:
f = DIR$
LOOP
END SUB</langsyntaxhighlight>
 
=={{header|BASIC256}}==
<langsyntaxhighlight BASIC256lang="basic256">call show ("c:\")
end
 
Line 439 ⟶ 514:
f$ = dir
end while
end subroutine</langsyntaxhighlight>
 
=={{header|Batch File}}==
A simple command that displays all EXE files in System32 directory non-recursively.
<langsyntaxhighlight lang="dos">dir /b "%windir%\system32\*.exe"</langsyntaxhighlight>
The same command inside FOR loop:
*Inside a Batch File:
<langsyntaxhighlight lang="dos">@for /F "tokens=*" %%F in ('dir /b "%windir%\system32\*.exe"') do echo %%F</langsyntaxhighlight>
*Command-line:
<langsyntaxhighlight lang="dos">for /F "tokens=*" %F in ('dir /b "%windir%\system32\*.exe"') do echo %F</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> directory$ = "C:\Windows\"
pattern$ = "*.ini"
PROClistdir(directory$ + pattern$)
Line 468 ⟶ 543:
SYS "FindClose", sh%
ENDIF
ENDPROC</langsyntaxhighlight>
 
=={{header|C}}==
Line 474 ⟶ 549:
{{works with|POSIX|.1-2001}}
In this example, the pattern is a [[POSIX]] extended regular expression.
<langsyntaxhighlight lang="c">#include <sys/types.h>
#include <dirent.h>
#include <regex.h>
Line 507 ⟶ 582:
walker(".", ".\\.c$");
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.IO;
 
Line 525 ⟶ 600:
}
}
</syntaxhighlight>
</lang>
 
=={{header|C++}}==
{{libheader|boost|1.50.0}}
<langsyntaxhighlight lang="cpp">#include "boost/filesystem.hpp"
#include "boost/regex.hpp"
#include <iostream>
Line 551 ⟶ 626:
}
}
}</langsyntaxhighlight>
 
{{libheader|std|C++17}}
<langsyntaxhighlight lang="cpp">
#include <filesystem>
#include <iostream>
Line 567 ⟶ 642:
std::cout << file.path().filename().string() << std::endl;
}
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
Using Java 8's [https://docs.oracle.com/javase/8/docs/api/java/nio/file/FileSystem.html#getPathMatcher-java.lang.String- PathMatcher] patterns.
 
<langsyntaxhighlight lang="clojure">(import java.nio.file.FileSystems)
 
(defn match-files [f pattern]
Line 580 ⟶ 655:
(let [directory (clojure.java.io/file dir)]
(map #(.getPath %) (filter #(match-files % pattern) (.listFiles directory)))))
</syntaxhighlight>
</lang>
 
=={{header|ColdFusion}}==
This example display all files and directories directly under '''C:\temp''' that end with ''.html''
<langsyntaxhighlight lang="cfm"><cfdirectory action="list" directory="C:\temp" filter="*.html" name="dirListing">
<cfoutput query="dirListing">
#dirListing.name# (#dirListing.type#)<br>
</cfoutput></langsyntaxhighlight>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun walk-directory (directory pattern)
(directory (merge-pathnames pattern directory)))</langsyntaxhighlight>
Uses the filename pattern syntax provided by the CL implementation.
 
=={{header|D}}==
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.file;
 
dirEntries(".", "*.*", SpanMode.shallow).writeln;
}</langsyntaxhighlight>
 
=={{header|DCL}}==
<pre>* matches any number of characters
& matches exactly any one character</pre>
<syntaxhighlight lang="text">$ loop:
$ f = f$search( p1 )
$ if f .eqs. "" then $ exit
$ write sys$output f
$ goto loop</langsyntaxhighlight>
{{out}}
<pre>$ @walk_a_directory *.*
Line 630 ⟶ 705:
 
{{libheader| System.IOUtils}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Walk_a_directory;
 
Line 655 ⟶ 730:
end.
 
</syntaxhighlight>
</lang>
 
{{out}}
Line 663 ⟶ 738:
 
=={{header|E}}==
<langsyntaxhighlight lang="e">def walkDirectory(directory, pattern) {
for name => file ? (name =~ rx`.*$pattern.*`) in directory {
println(name)
}
}</langsyntaxhighlight>
Example:
<langsyntaxhighlight lang="e">? walkDirectory(<file:~>, "bash_")
.bash_history
.bash_profile
.bash_profile~</langsyntaxhighlight>
 
=={{header|Elena}}==
ELENA 46.0x:
<langsyntaxhighlight lang="elena">import system'io;
import system'routines;
import extensions'routines;
Line 684 ⟶ 759:
var dir := Directory.assign("c:\MyDir");
dir.getFiles("a.*").forEach:(printingLn);
}</langsyntaxhighlight>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir"># current directory
IO.inspect File.ls!
 
dir = "/users/public"
IO.inspect File.ls!(dir)</langsyntaxhighlight>
 
{{out}}
Line 705 ⟶ 780:
directory, optionally restricted to those matching a regexp.
 
<langsyntaxhighlight lang="lisp">(directory-files "/some/dir/name"
nil ;; just the filenames, not full paths
"\\.c\\'" ;; regexp
t) ;; don't sort the filenames
;;=> ("foo.c" "bar.c" ...)</syntaxhighlight>
=>
("foo.c" "bar.c" ...)</lang>
 
=={{header|Erlang}}==
Line 725 ⟶ 799:
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">include file.e
 
procedure show(sequence pattern)
Line 736 ⟶ 810:
end procedure
 
show("*.*")</langsyntaxhighlight>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">System.IO.Directory.GetFiles("c:\\temp", "*.xml")
|> Array.iter (printfn "%s")</langsyntaxhighlight>
 
=={{header|Factor}}==
Using unix globs. Also see the "directory." in basis/tools/files.factor.
<langsyntaxhighlight lang="factor">USING: globs io io.directories kernel regexp sequences ;
IN: walk-directory-non-recursively
 
: print-files ( path pattern -- )
[ directory-files ] [ <glob> ] bi* [ matches? ] curry filter
[ print ] each ;</langsyntaxhighlight>
Ex:
( scratchpad ) "." "*.txt" print-files
Line 757 ⟶ 831:
{{works with|gforth|0.6.2}}
Gforth's directory walking functions are tied to the POSIX ''dirent'' functions, used by the C langauge entry above. Forth doesn't have regex support, so a simple filter function is used instead.
<langsyntaxhighlight lang="forth">defer ls-filter ( name len -- ? )
: ls-all 2drop true ;
: ls-visible drop c@ [char] . <> ;
Line 781 ⟶ 855:
' c-file? is ls-filter
 
s" ." ls</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
{{trans|BASIC}}
<langsyntaxhighlight lang="freebasic">
Sub show (pattern As String)
Dim As String f = Dir$(pattern)
Line 796 ⟶ 870:
show "*.*"
Sleep
</syntaxhighlight>
</lang>
 
=={{header|Frink}}==
This prints the names of all of the files in the current directory that end with <CODE>.frink</CODE> using a regular expression.
 
<langsyntaxhighlight lang="frink">for f = select[files["."], {|f1| f1.getName[] =~ %r/\.frink$/}]
println[f.getName[]]</langsyntaxhighlight>
 
{{out}}
Line 811 ⟶ 885:
graphicalSieve.frink
...
</pre>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"
 
void local fn EnumerateDirectoryAtURL( dirURL as CFURLRef )
NSDirectoryEnumerationOptions options = NSDirectoryEnumerationSkipsPackageDescendants + ¬
NSDirectoryEnumerationSkipsHiddenFiles + ¬
NSDirectoryEnumerationSkipsSubdirectoryDescendants
DirectoryEnumeratorRef enumerator = fn FileManagerEnumeratorAtURL( dirURL, NULL, options, NULL, NULL )
CFURLRef url = fn EnumeratorNextObject( enumerator )
while ( url )
if ( fn StringIsEqual( fn URLPathExtension( url ), @"fb" ) )
NSLog(@"%@",fn URLLastPathComponent( url ))
end if
url = fn EnumeratorNextObject( enumerator )
wend
end fn
 
fn EnumerateDirectoryAtURL( fn FileManagerURLForDirectory( NSDesktopDirectory, NSUserDomainMask ) )
 
HandleEvents
</syntaxhighlight>
 
{{out}}
<pre>
ListFormatter.fb
ObjectProperty1.fb
Archimedean Spiral with Bezier Curve.fb
FB3D.fb
lenArray.fb
Rosettacode Random Noise v04.fb
AssociatedObject.fb
</pre>
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=c5fde952fecd1d7052101b1e2287f2ff Click this link to run this code]'''
<langsyntaxhighlight lang="gambas">Public Sub Main()
Dim sTemp As String
Line 822 ⟶ 931:
Next
 
End</langsyntaxhighlight>
Output:
<pre>
Line 836 ⟶ 945:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 845 ⟶ 954:
func main() {
fmt.Println(filepath.Glob("*.go"))
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">// *** print *.txt files in current directory
new File('.').eachFileMatch(~/.*\.txt/) {
println it
Line 856 ⟶ 965:
new File('/foo/bar').eachFileMatch(~/.*\.txt/) {
println it
}</langsyntaxhighlight>
 
=={{header|Hare}}==
<syntaxhighlight lang="hare">use fmt;
use glob;
 
export fn main() void = {
ls("/etc/*.conf");
};
 
fn ls(pattern: str) void = {
let gen = glob::glob(pattern, glob::flags::NONE);
defer glob::finish(&gen);
for (true) match (glob::next(&gen)) {
case void =>
break;
case glob::failure =>
continue;
case let s: str =>
fmt::printfln("{}", s)!;
};
};</syntaxhighlight>
 
=={{header|Haskell}}==
{{works with|GHC|GHCi|6.6}}
In this example, the pattern is a POSIX extended regular expression.
<langsyntaxhighlight lang="haskell">import System.Directory
import Text.Regex
import Data.Maybe
Line 870 ⟶ 1,000:
mapM_ putStrLn $ filter (isJust.(matchRegex $ mkRegex pattern)) filenames
 
main = walk "." ".\\.hs$"</langsyntaxhighlight>
 
=={{header|HicEst}}==
More on [http://www.HicEst.com/SYSTEM.htm SYSTEM], [http://www.HicEst.com/OPEN.htm OPEN], [http://www.HicEst.com/indexfnc.htm INDEX]
<langsyntaxhighlight lang="hicest">CHARACTER dirtxt='dir.txt', filename*80
 
SYSTEM(DIR='*.*', FIle=dirtxt) ! "file names", length, attrib, Created, LastWrite, LastAccess
Line 883 ⟶ 1,013:
! write file names with extensions "txt", or "hic", or "jpg" (case insensitive) using RegEx option =128:
IF( INDEX(filename, "\.txt|\.hic|\.jpg", 128) ) WRITE() filename
ENDDO</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
This uses Unicon extensions for ''stat'' and to read directories. Icon can uses ''system'' to accomplish the same objective.
<langsyntaxhighlight Iconlang="icon">procedure main()
every write(getdirs(".","icn")) # writes out all directories from the current directory down
end
Line 900 ⟶ 1,030:
close(d)
}
end</langsyntaxhighlight>
 
=={{header|IDL}}==
<langsyntaxhighlight lang="idl">f = file_search('*.txt', count=cc)
if cc gt 0 then print,f</langsyntaxhighlight>
(IDL is an array language - very few things are ever done in 'loops'.)
 
=={{header|J}}==
<langsyntaxhighlight lang="j">require 'dir'
0 dir '*.png'
0 dir '/mydir/*.txt'</langsyntaxhighlight>
The verb <tt>dir</tt> supports a number of reporting options determined by its left argument. A left argument of <tt>0</tt> reports just the file names.
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">File dir = new File("/foo/bar");
 
String[] contents = dir.list();
for (String file : contents)
if (file.endsWith(".mp3"))
System.out.println(file);</langsyntaxhighlight>
 
=={{header|JavaScript}}==
{{works with|JScript}}
<langsyntaxhighlight lang="javascript">var fso = new ActiveXObject("Scripting.FileSystemObject");
var dir = fso.GetFolder('test_folder');
 
Line 944 ⟶ 1,074:
}
 
walkDirectory(dir, '\\.txt$');</langsyntaxhighlight>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">for filename in readdir("/foo/bar")
if endswith(filename, ".mp3")
print(filename)
end
end</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.2
 
import java.io.File
Line 970 ⟶ 1,100:
val files = walkDirectory("/usr/include", r)
for (file in files) println(file)
}</langsyntaxhighlight>
Sample output (Ubuntu v14.04):
{{out}}
Line 985 ⟶ 1,115:
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">local(matchingfilenames = array)
 
dir('.') -> foreach => {#1 >> 'string' ? #matchingfilenames -> insert(#1)}
 
#matchingfilenames</langsyntaxhighlight>
-> array(mystrings.html, a_string_file.txt)
 
=={{header|Lingo}}==
<langsyntaxhighlight lang="lingo">-- Usage: printFiles("C:\scripts", ".ls")
on printFiles (dir, fileType)
i = 1
Line 1,004 ⟶ 1,134:
if fn.char[fn.length-sub..fn.length]=fileType then put fn
end repeat
end</langsyntaxhighlight>
 
=={{header|LiveCode}}==
<langsyntaxhighlight LiveCodelang="livecode">set the defaultFolder to the documents folder -- the documents folder is a "specialFolderPath"
put the files into docfiles
filter docfiles with "*.txt"
put docfiles</langsyntaxhighlight>
 
=={{header|Lua}}==
Lua itself is extremely spartanic as it is meant for embedding. Reading out a directory is not something that a minimal standard C library can do, and so minimal Lua without native extension libraries can't do it either. But lfs (LuaFileSystem) is about as standard an extension as it gets, so we use that.
<langsyntaxhighlight Lualang="lua">require "lfs"
directorypath = "." -- current working directory
for filename in lfs.dir(directorypath) do
Line 1,020 ⟶ 1,150:
print(filename)
end
end</langsyntaxhighlight>
Although Lua is spartanic, it still provides functions such as os.execute([command]) and io.popen(prog [, mode]). Below an example for Windows users having io.popen at their disposal. Mind you, it may pop-up a command window.
<langsyntaxhighlight Lualang="lua">-- Gets the output of given program as string
-- Note that io.popen is not available on all platforms
local function getOutput(prog)
Line 1,052 ⟶ 1,182:
print(filename)
end
end</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
Line 1,060 ⟶ 1,190:
There is a second optional parameter which examine all files founded from first filter for included letters. We can add using | as seperator, a list of strings included in same line. Files examine all files, opened one by one, using an automatic way to find what kind of text file is, an Ansi, a Utf8, a Utf-16LE, or a Utf-16BE. Also automatic find the line breaks. All files converted at open as utf-16LE and then searched. For Ansi files, Locale used to make the right conversion.
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Show_Files_Standard {
\\ we get more (include hidden too)
Line 1,081 ⟶ 1,211:
}
Show_Files_Standard
</syntaxhighlight>
</lang>
 
Like VbScript using external help, from a COM object.
Line 1,091 ⟶ 1,221:
Stack New {} make a block of a fresh stack of values, and at the exit attach the old stack (which for this block detached from execute object at the begin of block).
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Show_Files {
Function get_files$ (folder_path$) {
Line 1,120 ⟶ 1,250:
}
Show_Files
</syntaxhighlight>
</lang>
 
=={{header|MathematicaMACRO-10}}==
<syntaxhighlight lang="macro-10">
TITLE DIRWLK - Directory Walker
SUBTTL PDP-10 Assembly Language (MACRO-10 @ TOPS-20). KJX 2022.
 
SEARCH MONSYM,MACSYM ;Get system-call names.
.REQUIRE SYS:MACREL ;Macros: TMSG, EJSHLT, etc.
 
STDAC. ;Define standard register names.
 
JFN: BLOCK 1 ;Space for JFN (file-handle)
FSPEC: BLOCK 20 ;Space for file specification.
FSPECL= <.-FSPEC>*5 ;Length in chars of file-spec.
 
GO:: RESET% ;Initialize process.
TMSG <Please enter filespec, wildcards are allowed: >
HRROI T1,FSPEC ;Read into FSPEC.
MOVEI T2,FSPECL ;Maximum allowed characters.
SETZ T3, ;No Ctrl-R prompting.
RDTTY% ;Read string from terminal.
EJSHLT ; Print error-msg on errors.
 
MOVX T1,GJ%OLD!GJ%IFG!GJ%FLG!GJ%SHT ;Various flags.
HRROI T2,FSPEC ;File specification from above.
GTJFN% ;Get JFN for first matching file.
EJSHLT ; Print error-msg on errors.
MOVEM T1,JFN ;Save JFN.
 
DO.
MOVEI T1,.PRIOU ;Write to standard-output.
HRRZ T2,JFN ;JFN from above to decode.
SETZ T3, ;No flags.
JFNS% ;Decode filename and print it.
EJSHLT ; Print error-msg on errors.
TMSG <
> ;Print newline.
MOVE T1,JFN ;Get JFN into T1.
GNJFN% ;Get next matching file.
JRST [ HALTF% ; Halt program on failure.
JRST GO ]
LOOP. ;No error: Do it again.
ENDDO.
 
END GO
</syntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
The built-in function <code>FileNames</code> does exactly this:
:<code>FileNames[]</code> lists all files in the current working directory.
Line 1,130 ⟶ 1,306:
:<code>FileNames[forms,dirs,n]</code> includes files that are in subdirectories up to n levels down.
Examples (find all files in current directory, find all png files in root directory):
<langsyntaxhighlight Mathematicalang="mathematica">FileNames["*"]
FileNames["*.png", $RootDirectory]</langsyntaxhighlight>
the result can be printed with Print /@ FileNames[....].
 
=={{header|MAXScript}}==
<langsyntaxhighlight lang="maxscript">getFiles "C:\\*.txt"</langsyntaxhighlight>
 
=={{header|Nanoquery}}==
<langsyntaxhighlight Nanoquerylang="nanoquery">import Nanoquery.IO
 
for fname in new(File).listDir("/foo/bar")
Line 1,144 ⟶ 1,320:
println filename
end
end</langsyntaxhighlight>
 
=={{header|Nemerle}}==
<langsyntaxhighlight Nemerlelang="nemerle">using System.Console;
using System.IO;
 
Line 1,159 ⟶ 1,335:
foreach (file in files) WriteLine(file);
}
}</langsyntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 1,196 ⟶ 1,372:
return
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,213 ⟶ 1,389:
Here is an example with <code>walkFiles</code> and a pattern:
 
<langsyntaxhighlight lang="nim">import os
 
for file in walkFiles "/foo/bar/*.mp3":
echo file</langsyntaxhighlight>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">use IO;
 
bundle Default {
Line 1,232 ⟶ 1,408:
}
}
}</langsyntaxhighlight>
 
=={{header|Objective-C}}==
<langsyntaxhighlight lang="objc">NSString *dir = @"/foo/bar";
 
// Pre-OS X 10.5
Line 1,244 ⟶ 1,420:
for (NSString *file in contents)
if ([[file pathExtension] isEqualToString:@"mp3"])
NSLog(@"%@", file);</langsyntaxhighlight>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">#load "str.cma"
let contents = Array.to_list (Sys.readdir ".") in
let select pat str = Str.string_match (Str.regexp pat) str 0 in
List.filter (select ".*\\.jpg") contents</langsyntaxhighlight>
 
=={{header|Odin}}==
<syntaxhighlight lang="odin">package main
 
import "core:fmt"
import "core:path/filepath"
 
main :: proc() {
matches, _err := filepath.glob("*.odin")
for match in matches do fmt.println(match)
}</syntaxhighlight>
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
[Path] = {Module.link ['x-oz://system/os/Path.ozf']}
[Regex] = {Module.link ['x-oz://contrib/regex']}
Line 1,261 ⟶ 1,448:
MatchingFiles = {Filter Files fun {$ File} {Regex.search Pattern File} \= false end}
in
{ForAll MatchingFiles System.showInfo}</langsyntaxhighlight>
 
=={{header|Pascal}}==
{{works with|Free Pascal}}
<langsyntaxhighlight lang="pascal">{$H+}
 
program Walk;
Line 1,295 ⟶ 1,482:
end;
FindClose(Res);
end.</langsyntaxhighlight>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use 5.010;
opendir my $dh, '/home/foo/bar';
say for grep { /php$/ } readdir $dh;
closedir $dh;</langsyntaxhighlight>
Or using globbing, with the <code>&lt;&gt;</code> operator,
<langsyntaxhighlight lang="perl">use 5.010; say while </home/foo/bar/*.php>;</langsyntaxhighlight>
Or the same with the builtin <code>glob()</code> function,
<langsyntaxhighlight lang="perl">my @filenames = glob('/home/foo/bar/*.php');</langsyntaxhighlight>
The <code>glob()</code> function takes any expression for its pattern, whereas <code>&lt;&gt;</code> is only for a literal.
<langsyntaxhighlight lang="perl">my $pattern = '*.c';
my @filenames = glob($pattern);</langsyntaxhighlight>
 
=={{header|Phix}}==
{{libheader|Phix/basics}}
The dir function accepts a DOS pattern, with some minor variations (eg "*" gets all files with no extension).
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">columnize</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">dir</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"*.txt"</span><span style="color: #0000FF;">))[</span><span style="color: #000000;">D_NAME</span><span style="color: #0000FF;">],</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">))</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 1,328 ⟶ 1,515:
=={{header|PHP}}==
{{works with|PHP|5.2.0}}
<langsyntaxhighlight lang="php">$pattern = 'php';
$dh = opendir('c:/foo/bar'); // Or '/home/foo/bar' for Linux
while (false !== ($file = readdir($dh)))
Line 1,340 ⟶ 1,527:
}
}
closedir($dh);</langsyntaxhighlight>
Or:
<langsyntaxhighlight lang="php">$pattern = 'php';
foreach (scandir('/home/foo/bar') as $file)
{
Line 1,352 ⟶ 1,539:
}
}
}</langsyntaxhighlight>
{{works with|PHP|<nowiki>4 >= 4.3.0 or 5</nowiki>}}
<langsyntaxhighlight lang="php">foreach (glob('/home/foo/bar/*.php') as $file){
echo "$file\n";
}</langsyntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(for F (dir "@src/") # Iterate directory
(when (match '`(chop "s@.c") (chop F)) # Matches 's*.c'?
(println F) ) ) # Yes: Print it</langsyntaxhighlight>
{{out}}
<pre>"start.c"
Line 1,370 ⟶ 1,557:
 
=={{header|Pike}}==
<langsyntaxhighlight lang="pike">array(string) files = get_dir("/home/foo/bar");
foreach(files, string file)
write(file + "\n");</langsyntaxhighlight>
 
=={{header|Pop11}}==
Built-in procedure sys_file_match searches directories (or directory trees) using shell-like patterns:
<langsyntaxhighlight lang="pop11">lvars repp, fil;
;;; create path repeater
sys_file_match('*.p', '', false, 0) -> repp;
Line 1,383 ⟶ 1,570:
;;; print the file
printf(fil, '%s\n');
endwhile;</langsyntaxhighlight>
 
=={{header|PowerShell}}==
Since PowerShell is also a shell it should come as no surprise that this task is very simple. Listing the names of all text files, or the names of all files, starting with "f":
<langsyntaxhighlight lang="powershell">Get-ChildItem *.txt -Name
Get-ChildItem f* -Name</langsyntaxhighlight>
The <code>-Name</code> parameter tells the <code>Get-ChildItem</code> to return only the file names as string, otherwise a complete <code>FileInfo</code> or <code>DirectoryInfo</code> object would be returned, containing much more information than only the file name.
 
More complex matching can be accomplished by filtering the complete list of files using the <code>Where-Object</code> cmdlet. The following will output all file names that contain at least one vowel:
<langsyntaxhighlight lang="powershell">Get-ChildItem -Name | Where-Object { $_ -match '[aeiou]' }</langsyntaxhighlight>
 
=={{header|PureBasic}}==
The match is made using DOS wildcards. It could easily be modified to match based on a regular expression if desired (i.e. using the PCRE library).
<langsyntaxhighlight PureBasiclang="purebasic">Procedure walkDirectory(directory.s = "", pattern.s = "")
Protected directoryID
Line 1,414 ⟶ 1,601:
Input()
CloseConsole()
EndIf</langsyntaxhighlight>
 
=={{header|Python}}==
The [http://python.org/doc/lib/module-glob.html glob] library included with Python lists files matching shell-like patterns:
<langsyntaxhighlight lang="python">import glob
for filename in glob.glob('/foo/bar/*.mp3'):
print(filename)</langsyntaxhighlight>
Or manually:
<langsyntaxhighlight lang="python">import os
for filename in os.listdir('/foo/bar'):
if filename.endswith('.mp3'):
print(filename)</langsyntaxhighlight>
 
=={{header|R}}==
<langsyntaxhighlight Rlang="r">dir("/foo/bar", "mp3")</langsyntaxhighlight>
 
=={{header|Racket}}==
 
<syntaxhighlight lang="racket">
<lang Racket>
-> (for ([f (directory-list "/tmp")] #:when (regexp-match? "\\.rkt$" f))
(displayln f))
... *.rkt files ...
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
The <code>dir</code> function takes the directory to traverse, and optionally a named parameter <code>test</code>, which is [https://docs.raku.org/routine/$TILDE$TILDE smart-matched] against the basename of each file (so for example we can use a regex):
<syntaxhighlight lang="raku" perl6line>.say for dir ".", :test(/foo/);</langsyntaxhighlight>
 
=={{header|Rascal}}==
<langsyntaxhighlight lang="rascal">import IO;
public void Walk(loc a, str pattern){
for (entry <- listEntries(a))
endsWith(entry, pattern) ? println(entry);
}</langsyntaxhighlight>
 
=={{header|Raven}}==
<langsyntaxhighlight lang="raven">'dir://.' open each as item
item m/\.txt$/ if "%(item)s\n" print</langsyntaxhighlight>
 
=={{header|REXX}}==
{{works with|Regina}}
The following program was tested in a DOS window under Windows/XP and should work for all Microsoft Windows.
<langsyntaxhighlight lang="rexx">/*REXX program shows files in directory tree that match a given criteria*/
parse arg xdir; if xdir='' then xdir='\' /*Any DIR? Use default.*/
@.=0 /*default in case ADDRESS fails. */
Line 1,473 ⟶ 1,660:
do j=1 for #; say @.j; end /*show files that met criteria. */
 
exit @.0+rc /*stick a fork in it, we're done.*/</langsyntaxhighlight>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
 
###---------------------------------------
Line 1,567 ⟶ 1,754:
###===============================================
 
</syntaxhighlight>
</lang>
 
OUTPUT:
Line 1,627 ⟶ 1,814:
Finished
 
</pre>
 
=={{header|RPL}}==
{{works with|Halcyon Calc|4.2.7}}
The very first instruction of this program <code>VARS</code> returns the list of all current files and subdirectories. The rest of the code retains the names that comply with the pattern given in input, and which are not directories. To do so, the program attempts to recall the contents of each object on the stack through <code>RCL</code>: if an error occurs, the object is then a directory and shall not be processed further.
≪ VARS → filter list
≪ { } 1 list SIZE '''FOR''' j
list j GET
'''IFERR''' DUP RCL '''THEN''' DROP2
'''ELSE'''
DROP →STR 2 OVER SIZE 1 - SUB
'''IF''' DUP filter POS '''THEN''' + ELSE DROP '''END'''
'''END'''
'''NEXT'''
≫ ≫
'WKDIR' STO
 
"T" WKDIR
{{out}}
<pre>
1: { "T" "TESTPGM" "FACTN" }
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby"># Files under this directory:
Dir.glob('*') { |file| puts file }
 
Line 1,641 ⟶ 1,849:
puts file if file =~ pattern
end
end</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">files #g, DefaultDir$ + "\*.jpg" ' find all jpg files
if #g HASANSWER() then
Line 1,655 ⟶ 1,863:
next
end if
wait</langsyntaxhighlight>
FILE ACCESSOR methods
 
Line 1,683 ⟶ 1,891:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">extern crate docopt;
extern crate regex;
extern crate rustc_serialize;
Line 1,718 ⟶ 1,926:
}
}
}</langsyntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight Scalalang="scala">import java.io.File
 
val dir = new File("/foo/bar").list()
dir.filter(file => file.endsWith(".mp3")).foreach(println)</langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "osfiles.s7i";
 
Line 1,739 ⟶ 1,947:
end if;
end for;
end func;</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">'*.p[lm]'.glob.each { |file| say file } # Perl files under this directory</langsyntaxhighlight>
{{out}}
<pre>
Line 1,749 ⟶ 1,957:
</pre>
 
<langsyntaxhighlight lang="ruby">func file_match(Block callback, pattern=/\.txt\z/, path=Dir.cwd) {
path.open(\var dir_h) || return nil
dir_h.entries.each { |entry|
Line 1,764 ⟶ 1,972:
say file;
}
)</langsyntaxhighlight>
{{out}}
<pre>
Line 1,772 ⟶ 1,980:
 
=={{header|Smalltalk}}==
<langsyntaxhighlight lang="smalltalk">(Directory name: 'a_directory')
allFilesMatching: '*.st' do: [ :f | (f name) displayNl ]</langsyntaxhighlight>
 
=={{header|Standard ML}}==
<langsyntaxhighlight lang="sml">fun dirEntries path =
let
fun loop strm =
Line 1,785 ⟶ 1,993:
in
loop strm before OS.FileSys.closeDir strm
end</langsyntaxhighlight>
List all "hidden" files (starting with a dot in Unix) in the current directory:
<langsyntaxhighlight lang="sml">(print o concat o map (fn s => s ^ "\n") o List.filter (String.isPrefix ".") o dirEntries) "."</langsyntaxhighlight>
 
=={{header|Tcl}}==
For the current directory:
<langsyntaxhighlight lang="tcl">foreach filename [glob *.txt] {
puts $filename
}</langsyntaxhighlight>
For an arbitrary directory:
<langsyntaxhighlight lang="tcl">set dir /foo/bar
foreach filename [glob -directory $dir *.txt] {
puts $filename
### Or, if you only want the local filename part...
# puts [file tail $filename]
}</langsyntaxhighlight>
 
=={{header|Toka}}==
As with the C example, this uses a a POSIX extended regular expression as the pattern. The '''dir.listByPattern''' function used here was introduced in library revision 1.3.
<langsyntaxhighlight lang="toka">needs shell
" ." " .\\.txt$" dir.listByPattern</langsyntaxhighlight>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">$$ MODE TUSCRIPT
files=FILE_NAMES (+,-std-)
fileswtxt= FILTER_INDEX (files,":*.txt:",-)
txtfiles= SELECT (files,#fileswtxt)</langsyntaxhighlight>
{{out}}
<pre>
Line 1,823 ⟶ 2,031:
==== Using <code>glob</code> ====
 
<langsyntaxhighlight lang="txrlisp">(glob "/etc/*.conf")</langsyntaxhighlight>
 
{{out}}
 
<langsyntaxhighlight lang="txrlisp">("/etc/adduser.conf" "/etc/apg.conf" "/etc/blkid.conf" "/etc/brltty.conf"
"/etc/ca-certificates.conf" "/etc/colord.conf" "/etc/ddclient.conf"
"/etc/debconf.conf" "/etc/deluser.conf" "/etc/dnsmasq.conf" "/etc/ffserver.conf"
Line 1,837 ⟶ 2,045:
"/etc/pnm2ppa.conf" "/etc/popularity-contest.conf" "/etc/resolv.conf"
"/etc/rsyslog.conf" "/etc/sensors3.conf" "/etc/sysctl.conf" "/etc/ucf.conf"
"/etc/updatedb.conf" "/etc/usb_modeswitch.conf" "/etc/wodim.conf")</langsyntaxhighlight>
 
==== Using <code>open-directory</code> and <code>get-lines</code> ====
 
<langsyntaxhighlight lang="txrlisp">(mappend [iff (op ends-with ".conf") list] (get-lines (open-directory "/etc")))</langsyntaxhighlight>
 
{{out}}
 
<langsyntaxhighlight lang="txrlisp">("ddclient.conf" "gai.conf" "ucf.conf" "kernel-img.conf" "ltrace.conf"
"debconf.conf" "apg.conf" "adduser.conf" "mke2fs.conf" "colord.conf"
"kerneloops.conf" "fuse.conf" "hdparm.conf" "irssi.conf" "host.conf"
Line 1,853 ⟶ 2,061:
"knockd.conf" "ntp.conf" "sensors3.conf" "resolv.conf" "blkid.conf"
"lftp.conf" "ca-certificates.conf" "usb_modeswitch.conf" "logrotate.conf"
"rsyslog.conf" "pnm2ppa.conf")</langsyntaxhighlight>
 
=={{header|UNIX Shell}}==
<langsyntaxhighlight lang="bash">ls -d *.c # *.c files in current directory
(cd mydir && ls -d *.c) # *.c files in mydir</langsyntaxhighlight>
<code>*.c</code> is a ''file name pattern'', also known as a ''glob pattern''. The shell expands each pattern to a sorted list of matching files. Details are in your shell's manual.
 
Line 1,864 ⟶ 2,072:
=={{header|UnixPipes}}==
Here using grep for regexp.
<langsyntaxhighlight lang="bash">ls | grep '\.c$'</langsyntaxhighlight>
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
Sub show_files(folder_path,pattern)
Set objfso = CreateObject("Scripting.FileSystemObject")
Line 1,878 ⟶ 2,086:
 
Call show_files("C:\Windows",".exe")
</syntaxhighlight>
</lang>
 
=={{header|Visual Basic .NET}}==
{{works with|Visual Basic .NET|9.0+}}
<langsyntaxhighlight lang="vbnet">'Using the OS pattern matching
For Each file In IO.Directory.GetFiles("\temp", "*.txt")
Console.WriteLine(file)
Line 1,895 ⟶ 2,103:
For Each file In IO.Directory.GetFiles("\temp").Where(Function(f) f Like "*.txt")
Console.WriteLine(file)
Next</langsyntaxhighlight>
 
=={{header|Wren}}==
{{libheader|Wren-pattern}}
<langsyntaxhighlight ecmascriptlang="wren">import "io" for Directory
import "./pattern" for Pattern
 
var walk = Fn.new { |dir, pattern|
Line 1,910 ⟶ 2,118:
// get all C header files beginning with 'a' or 'b'
var p = Pattern.new("[a|b]+0^..h", Pattern.whole)
for (f in walk.call("/usr/include", p)) System.print(f)</langsyntaxhighlight>
 
{{out}}
Line 1,927 ⟶ 2,135:
=={{header|zkl}}==
Unix glob, with wildcarding and options on file type, case folding and a few others.
<langsyntaxhighlight lang="zkl">File.glob("*.zkl") //--> list of matches</langsyntaxhighlight>
 
=={{header|Zsh}}==
Zsh has powerful filename generation features, which can filter by file names, permissions, size, type, etc.
<langsyntaxhighlight lang="bash">print -l -- *.c</langsyntaxhighlight>
 
{{omit from|AWK|Use a shell command: system("ls *.awk")}}
9,482

edits