Unix/ls: Difference between revisions

28,855 bytes added ,  3 months ago
m
→‎{{header|Wren}}: Changed to Wren S/H
m (→‎{{header|REXX}}: added wording.)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(28 intermediate revisions by 21 users not shown)
Line 33:
</pre>
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">print(sorted(fs:list_dir(‘.’)).join("\n"))</syntaxhighlight>
 
=={{header|8080 Assembly}}==
Line 39 ⟶ 44:
filenames in sorted order, so it has to do the sorting itself.
 
<langsyntaxhighlight lang="8080asm">dma: equ 80h
puts: equ 9h ; Write string to console
sfirst: equ 11h ; Find first matching file
Line 171 ⟶ 176:
fcb: db 0,'???????????' ; Accept any file
ds fcb+36-$ ; Pad the FCB out to 36 bytes
fnames:</langsyntaxhighlight>
 
 
=={{header|8th}}==
<langsyntaxhighlight lang="forth">
"*" f:glob
' s:cmp a:sort
"\n" a:join .
</syntaxhighlight>
</lang>
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, Ada.Directories, Ada.Containers.Indefinite_Vectors;
 
procedure Directory_List is
Line 213 ⟶ 217:
Put_Line(Result.Element(I));
end loop;
end Directory_List;</langsyntaxhighlight>
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">record r;
file f;
text s;
Line 228 ⟶ 232:
}
 
r.vcall(o_, 0, "\n");</langsyntaxhighlight>
 
=={{header|Arturo}}==
 
<langsyntaxhighlight arturolang="rebol">print [dirContentlist "."]</langsyntaxhighlight>
 
=={{header|AWK}}==
{{works with|gawk}} "BEGINFILE" is a gawk-extension
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f UNIX_LS.AWK * | SORT
BEGINFILE {
Line 245 ⟶ 249:
exit(0)
}
</syntaxhighlight>
</lang>
 
Sample commands and output under Windows 8:
Line 278 ⟶ 282:
 
=={{header|BaCon}}==
<langsyntaxhighlight lang="freebasic">' Emulate ls
cnt% = 0
files$ = ""
Line 295 ⟶ 299:
PRINT FLATTEN$(f$)
NEXT
ENDIF</langsyntaxhighlight>
 
 
=={{header|BASIC256}}==
<syntaxhighlight lang="basic256">directory$ = dir("m:\foo\bar\") #Specified directory
#directory$ = dir(currentdir) #Current directory
 
while directory$ <> ""
print directory$
directory$ = dir()
end while
end</syntaxhighlight>
 
 
=={{header|C}}==
C does not have any os-independent way of reading a directory. The following uses readdir and should work on any Unix system.
<syntaxhighlight lang="c">
<lang C>
#include <stdio.h>
#include <stdlib.h>
Line 363 ⟶ 379:
return 0;
}
</syntaxhighlight>
</lang>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.IO;
Line 390 ⟶ 406:
}
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
{{libheader|Boost}}
<langsyntaxhighlight lang="cpp">
#include <iostream>
#include <set>
Line 412 ⟶ 428:
std::cout << entry << '\n';
}
</syntaxhighlight>
</lang>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(def files (sort (filter #(= "." (.getParent %)) (file-seq (clojure.java.io/file ".")))))
 
(doseq [n files] (println (.getName n)))</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
Line 425 ⟶ 441:
The workhorse is `files-list`, which returns a list of filenames. The `ls` function sorts the resulting list and formats it for output.
 
<langsyntaxhighlight lang="lisp">(defun files-list (&optional (path "."))
(let* ((dir (concatenate 'string path "/"))
(abs-path (car (directory dir)))
Line 436 ⟶ 452:
 
(defun ls (&optional (path "."))
(format t "~{~a~%~}" (sort (files-list path) #'string-lessp)))</langsyntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.file, std.path, std.array, std.algorithm;
 
foreach (const string path; dirEntries(getcwd, SpanMode.shallow).array.sort)
path.baseName.writeln;
}</langsyntaxhighlight>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| System.IoUtils}}
<syntaxhighlight lang="delphi">
program LsCommand;
 
{$APPTYPE CONSOLE}
 
 
 
uses
System.SysUtils,
System.IoUtils;
 
procedure Ls(folder: string = '.');
var
offset: Integer;
fileName: string;
 
// simulate unix results in windows
 
function ToUnix(path: string): string;
begin
Result := path.Replace('/', PathDelim, [rfReplaceAll])
end;
 
begin
folder := IncludeTrailingPathDelimiter(ToUnix(folder));
offset := length(folder);
 
for fileName in TDirectory.GetFileSystemEntries(folder, '*') do
writeln(^I, ToUnix(fileName).Substring(offset));
end;
 
begin
writeln('cd foo'#10'ls');
ls('foo');
 
writeln(#10'cd bar'#10'ls');
ls('foo/bar');
 
{$IFNDEF LINUX} readln; {$ENDIF}
end.</syntaxhighlight>
{{out}}
<pre>cd foo
ls
bar
 
cd bar
ls
1
2
a
b</pre>
 
=={{header|EchoLisp}}==
No directory in EchoLisp, which is run in a browser window. Instead, "stores" (folders) and keys in stores (file names) are located in local storage.
<langsyntaxhighlight lang="lisp">
;; ls of stores (kind of folders)
(for-each writeln (list-sort < (local-stores))) →
Line 465 ⟶ 535:
Glory
Jonah
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">iex(1)> ls = fn dir -> File.ls!(dir) |> Enum.each(&IO.puts &1) end
#Function<6.54118792/1 in :erl_eval.expr/5>
iex(2)> ls.("foo")
Line 478 ⟶ 548:
a
b
:ok</langsyntaxhighlight>
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">
1> Ls = fun(Dir) ->
1> {ok, DirContents} = file:list_dir(Dir),
Line 496 ⟶ 566:
b
[ok,ok,ok,ok]
</syntaxhighlight>
</lang>
 
=={{header|F_Sharp|F#}}==
<p>Works with .NET framework 4.</p>
<langsyntaxhighlight lang="fsharp">let ls = DirectoryInfo(".").EnumerateFileSystemInfos() |> Seq.map (fun i -> i.Name) |> Seq.sort |> Seq.iter (printfn "%s")</langsyntaxhighlight>
<p>Prior to .NET4 you had to enumerate files and directories separately.</p>
<p>The call to <code>sort</code> is probably redundant, since "sorted by name" seems to be the default in Windows.</p>
Line 506 ⟶ 576:
=={{header|Forth}}==
This is much easier without the 'sorted output' requirement:
<langsyntaxhighlight lang="forth">256 buffer: filename-buf
: each-filename { xt -- } \ xt-consuming variant
s" ." open-dir throw { d }
Line 517 ⟶ 587:
: ]each-filename ]] repeat drop r> close-dir throw [[ ; immediate compile-only
 
: ls ( -- ) [: cr type ;] each-filename ;</langsyntaxhighlight>
 
Given that requirement, we must first generate a sorted array of filenames:
{{libheader|Forth Foundation Library}}
<langsyntaxhighlight lang="forth">: save-string ( c-addr u -- a )
dup 1+ allocate throw dup >r place r> ;
 
Line 536 ⟶ 606:
: ls ( -- )
[: count cr type ;] each-sorted-filename ;
</syntaxhighlight>
</lang>
 
=={{header|Fortran}}==
This is possible only for those Fortran compilers that offer some sort of interface with the operating system's file handling routines. Not standard at all! <langsyntaxhighlight Fortranlang="fortran"> PROGRAM LS !Names the files in the current directory.
USE DFLIB !Mysterious library.
TYPE(FILE$INFO) INFO !With mysterious content.
Line 556 ⟶ 626:
END IF !So much for that entry.
IF (MARK.NE.FILE$LAST) GO TO 10 !Lastness is discovered after the last file is fingered.
END !If FILE$LAST is not reached, "system resources may be lost." </langsyntaxhighlight>
This relies on the supplied routine GETFILEINFOQQ, which is not at all a standard routine, but it does behave in the same way as is found in many other systems, notably with a file name selection filter, here chosen to be "*" meaning "any file". It supplies successive file names and requires mysterious parameters to keep track of what it is doing. In the installation file C:/Compilers/Furrytran/Compaq Furrytran 6.6a CD/X86/DF/INCLUDE/DFLIB.F90, there is the following segment: <langsyntaxhighlight Fortranlang="fortran"> INTERFACE
INTEGER*4 FUNCTION GETFILEINFOQQ(FILES, BUFFER,dwHANDLE)
!DEC$ ATTRIBUTES DEFAULT :: GETFILEINFOQQ
Line 572 ⟶ 642:
INTEGER*4 dwHANDLE
END FUNCTION
END INTERFACE</langsyntaxhighlight>
Getting this to work was quite annoying. It turned out that the irritating "files" . and .. are deemed a directory (via the bit in INFO.PERMIT matching that of FILE$DIR = 16) and so can be skipped along with proper subdirectories, but the "PERMIT" value of -1 returned for the FILE$LAST state also matches, though its (non-existent) file name length is given as zero. Thus, if one skips directories filter-style by IF ... GO TO 10, in such a case the end will never be seen. Further, although Fortran syntax allows <code>INFO.PERMIT .AND. FILE$DIR</code> the bit values of logical variables are strange. Instead, what is needed is <code>IAND(INFO.PERMIT,FILE$DIR)</code>
 
Line 578 ⟶ 648:
 
As for the ordering of results, on this Windows XP system, the file names came out ordered so there is no need to mess about with a storage area to sort the names in.
 
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">#include "dir.bi"
 
Sub ls(Byref filespec As String, Byval attrib As Integer)
Dim As String filename = Dir(filespec, attrib)
Do While Len(filename) > 0
Print filename
filename = Dir()
Loop
End Sub
 
Dim As String directory = "" ' Current directory
ls(directory & "*", fbDirectory)
Sleep</syntaxhighlight>
 
=={{header|Frink}}==
<syntaxhighlight lang="frink">for f = sort[files["."], {|a,b| lexicalCompare[a.getName[], b.getName[]]}]
println[f.getName[]]</syntaxhighlight>
 
=={{header|FunL}}==
<langsyntaxhighlight lang="funl">import io.File
 
for f <- sort( list(File( "." ).list()).filterNot(s -> s.startsWith(".")) )
println( f )</langsyntaxhighlight>
 
{{out}}
Line 610 ⟶ 700:
The output is indeed sorted, but not all filetypes alltogether: the sorting algorythm is invoked for the different filetypes separately, because it is the way I like it!
 
<syntaxhighlight lang="furor">
<lang Furor>
###sysinclude dir.uh
###sysinclude stringextra.uh
Line 691 ⟶ 781:
{ „temp” }
{ „makestring” #s * dup 10 !+ swap free #g = }
</syntaxhighlight>
</lang>
 
{{out}}
Line 760 ⟶ 850:
for non-privilegized use: 13951995904 ( 11% )
All available free space: 20411224064 ( 16% )
 
</pre>
 
It is not visible on the output above, but the digits in the filesize are colored, each 3 digits has different color.
 
=={{header|Peri}}==
The following program lists just the subdirectories, regular files and symlinks, because I do no need the other gizmos generally, but based on these abovementioned file types it is easy to expand with them, if it is necessary.
 
The output is indeed sorted, but not all filetypes alltogether: the sorting algorythm is invoked for the different filetypes separately, because it is the way I like it!
 
<syntaxhighlight lang="peri">
###sysinclude standard.uh
###sysinclude args.uh
###sysinclude io.uh
###sysinclude str.uh
 
###define COLORS
// delete the COLORS directive above if you do not want colored output!
#g argc 3 < { "." }{ 2 argv } sto mypath
@mypath 'd inv istrue { ."The given directory doesn't exist! Exited.\n" end }
@mypath getdir { ."Cannot load the dir! Aborted.\n" end } sto mydir
'- 90 *... sto vonal
'. 60 *... sto points
 
@mydir ~d {
."Directories:\n"
@mydir ~d {{ #s
@mydir 'd {{}} octalrights dup print inv mem SPACE
@mydir 'd {{}} getfilename dup 67 mc print SPACE drop
@mydir 'd {{}} groupname ': !+
@mydir 'd {{}} ownername dup sto temp + dup 10 mc print inv mem @temp inv mem
@mydir 'd {{}} mtime dup print inv mem
NL }}
@points sprintnl
@mydir ~d { ."Total: " @mydir ~d #g print ." subdirectories.\n" }
@vonal sprintnl
}
 
@mydir ~r {
."Regular files:\n"
@mydir ~r {{ #s
@mydir 'r {{}} octalrights dup print inv mem SPACE
@mydir 'r {{}} getfilesize sbr §ifcolored
@mydir 'r {{}} executable { ." >" }{ ." " } SPACE
@mydir 'r {{}} getfilename dup 67 mc print SPACE drop
@mydir 'r {{}} groupname ': !+
@mydir 'r {{}} ownername dup sto temp + dup 10 mc print inv mem @temp inv mem
@mydir 'r {{}} mtime dup print inv mem
NL }}
@points sprintnl
@mydir ~r { ."Total: " @mydir ~r #g print ." regular files. "
."TotalSize = " @mydir 'r totalsize sbr §ifcolored NL
}
@vonal sprintnl
}
@mydir ~L {
."Symlinks:\n"
@mydir ~L {{ #s
@mydir 'L {{}} octalrights dup print inv mem SPACE
@mydir 'L {{}} executable { .">" }{ SPACE } SPACE
@mydir 'L {{}} getfilename dup 67 mc print SPACE drop
@mydir 'L {{}} broken { ."--->" }{ ."===>" } SPACE
@mydir 'L {{}} destination dup 30 mc print drop
NL }}
@points sprintnl
@mydir ~L { ."Total: " @mydir ~L #g print ." symlinks.\n"
}
}
@vonal sprintnl
."Size, alltogether = " @mydir alltotal sbr §ifcolored NL
@vonal sprintnl
 
 
@mydir inv mem
 
."free spaces: /* Total size of the filesystem is : " @mypath filesystemsize dup sto filsize sbr §ifcolored ." */\n"
." for non-privilegized use: " @mypath freenonpriv dup sbr §ifcolored
#g 100 * @filsize / ." ( " print ."% ) " NL
." All available free space: " @mypath totalfree dup sbr §ifcolored
#g 100 * @filsize / ." ( " print ."% ) " NL
@vonal inv mem
end
 
ifcolored:
###ifdef COLORS
coloredsize
###endif
###ifndef COLORS
#g !(#s) 21 >|
###endif
dup sprint inv mem
rts
 
{ „filsize” }
{ „mydir” }
{ „mypath” }
{ „temp” }
{ „vonal” }
{ „points” }
 
 
</syntaxhighlight>
 
{{out}}
<pre>
Directories:
0775 arrays vz:vz 2020.11.15 22:44:49 V
0775 examples vz:vz 2021.02.05 22:58:48 P
0775 headers vz:vz 2021.01.19 20:34:07 K
0775 inaneheaders vz:vz 2021.02.21 18:59:46 V
0775 keyboardlayout_files vz:vz 2021.09.10 21:51:11 P
0775 libraries vz:vz 2021.09.10 22:20:04 P
0775 Peri_newlinkerhez root:root 2022.06.19 18:53:37 V
0775 patterns vz:vz 2021.02.21 17:24:35 V
0775 perifonts vz:vz 2020.05.09 10:46:19 Szo
0775 tests vz:vz 2020.11.08 14:44:31 V
0775 useful vz:vz 2022.01.27 12:16:31 Cs
............................................................
Total: 11 subdirectories.
------------------------------------------------------------------------------------------
Regular files:
0664 3379 __peri.c vz:vz 2020.11.08 14:35:28 V
0664 938037 A_Peri_programozasi_nyelv.odt vz:vz 2022.02.16 16:10:56 Sze
0664 9185 castingoperators.c vz:vz 2020.12.30 20:19:48 Sze
0664 27148 inanerun.c vz:vz 2021.01.26 12:52:53 K
0664 14998 jumpingtable.c vz:vz 2021.01.26 12:52:19 K
0664 15862 keywords.c vz:vz 2021.01.26 12:46:02 K
0664 3110 libraries.sh vz:vz 2020.12.04 02:46:13 P
0664 1114 Makefile vz:vz 2020.11.08 14:12:28 V
0664 257 mybmi.upu vz:vz 2022.01.27 12:15:03 Cs
0775 10279 > peri vz:vz 2021.09.10 22:20:04 P
0664 34225 postfixoperators.c vz:vz 2021.01.01 00:16:45 P
0644 563 preinitpostmortem.c vz:vz 2020.10.25 15:48:55 V
0664 119 printitself.upu vz:vz 2023.03.21 22:23:24 K
0664 929840 The_Peri_programming_language.odt vz:vz 2021.09.10 22:23:22 P
0644 8357 UPU.syntax vz:vz 2021.01.06 18:00:58 Sze
0664 2199 verify.upu vz:vz 2020.11.29 23:07:42 V
............................................................
Total: 16 regular files. TotalSize = 1998672
------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------
Size, alltogether = 2043728
------------------------------------------------------------------------------------------
free spaces: /* Total size of the filesystem is : 126693117952 */
for non-privilegized use: 35734585344 ( 28% )
All available free space: 42193813504 ( 33% )
 
</pre>
Line 766 ⟶ 1,002:
 
=={{header|Gambas}}==
<langsyntaxhighlight lang="gambas">Public Sub Main()
Dim sDir As String[] = Dir(User.Home &/ "test").Sort()
 
Print sDir.Join(gb.NewLine)
 
End</langsyntaxhighlight>
Output:
<pre>
Line 782 ⟶ 1,018:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 805 ⟶ 1,041:
fmt.Println(n)
}
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
Line 811 ⟶ 1,047:
{{Works with|GHC|7.8.3}}
 
<langsyntaxhighlight lang="haskell">import Control.Monad
import Data.List
import System.Directory
Line 819 ⟶ 1,055:
main = do
files <- getDirectoryContents "."
mapM_ putStrLn $ sort $ filter (dontStartWith '.') files</langsyntaxhighlight>
 
=={{header|J}}==
See the [http://www.jsoftware.com/wsvn/base8/trunk/main/main/dir.ijs dir.ijs script] for a full description of the interface for <code>dir</code>:
<langsyntaxhighlight Jlang="j"> dir '' NB. includes properties
>1 1 dir '' NB. plain filename as per task</langsyntaxhighlight>
 
=={{header|Java}}==
This is a generic implementation using the basic ''File'' methods.
<syntaxhighlight lang="java">
import java.io.File;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.List;
 
public class Ls {
public static void main(String[] args) throws Exception {
Ls ls = new Ls("/");
System.out.println(ls);
}
 
private final File directory;
private final List<File> list;
 
public Ls(String path) throws Exception {
directory = new File(path);
if (!directory.exists())
throw new Exception("Path not found '%s'".formatted(directory));
if (!directory.isDirectory())
throw new Exception("Not a directory '%s'".formatted(directory));
list = new ArrayList<>(List.of(directory.listFiles()));
/* place the directories first */
list.sort((fileA, fileB) -> {
if (fileA.isDirectory() && fileB.isFile()) {
return -1;
} else if (fileA.isFile() && fileB.isDirectory()) {
return 1;
}
return 0;
});
}
 
private String size(long bytes) {
if (bytes > 1E9) {
return "%.1fG".formatted(bytes / 1E9d);
} else if (bytes > 1E6) {
return "%.1fM".formatted(bytes / 1E6d);
} else if (bytes > 1E3) {
return "%.1fK".formatted(bytes / 1E3d);
} else {
return "%d".formatted(bytes);
}
}
 
@Override
public String toString() {
StringBuilder string = new StringBuilder();
Formatter formatter = new Formatter(string);
/* add parent and current directory listings */
list.add(0, directory.getParentFile());
list.add(0, directory);
/* generate total used space value */
long total = 0;
for (File file : list) {
if (file == null) continue;
total += file.length();
}
formatter.format("total %s%n", size(total));
/* generate output for each entry */
int index = 0;
for (File file : list) {
if (file == null) continue;
/* generate permission columns */
formatter.format(file.isDirectory() ? "d" : "-");
formatter.format(file.canRead() ? "r" : "-");
formatter.format(file.canWrite() ? "w" : "-");
formatter.format(file.canExecute() ? "x" : "-");
/* include size */
formatter.format("%7s ", size(file.length()));
/* modification timestamp */
formatter.format("%tb %1$td %1$tR ", file.lastModified());
/* file or directory name */
switch (index) {
case 0 -> formatter.format(".");
case 1 -> formatter.format("..");
default -> formatter.format("%s", file.getName());
}
if (file.isDirectory())
formatter.format(File.separator);
formatter.format("%n");
index++;
}
formatter.flush();
return string.toString();
}
}
</syntaxhighlight>
<pre>
total 22.3K
dr-x 154 Feb 13 02:48 ./
dr-x 10.9K Apr 14 20:17 ../
dr-x 0 Dec 09 14:15 boot/
dr-x 660 May 12 20:48 dev/
dr-x 2.3K May 12 20:48 etc/
dr-x 12 Apr 14 20:12 home/
dr-x 614 Apr 15 15:00 lib/
dr-x 1.1K Apr 15 15:00 lib32/
dr-x 46 Feb 13 02:48 lib64/
dr-x 1.1K Apr 15 15:00 libx32/
dr-x 0 Feb 13 02:47 media/
dr-x 32 Apr 14 20:12 mnt/
dr-x 40 Apr 14 20:18 opt/
dr-x 0 May 12 20:48 proc/
d--- 30 Feb 13 02:47 root/
dr-x 400 May 12 20:48 run/
dr-x 4.2K Feb 13 02:48 sbin/
dr-x 0 Feb 13 02:47 srv/
dr-x 0 May 12 20:48 sys/
drwx 566 May 13 00:41 tmp/
dr-x 116 Feb 13 02:47 usr/
dr-x 90 Feb 13 02:47 var/
</pre>
<br />
An alternate demonstration
{{Works with|Java|11}}
 
<langsyntaxhighlight lang="java">
package rosetta;
 
Line 842 ⟶ 1,194:
}
}
</syntaxhighlight>
</lang>
 
The challenge does not state that the files must be sorted in case-insensitive order, and the majority of solutions in other languages do not bother with same.
The above can be expanded to sort case-insensitively by mapping Path to String and using the predefined String Comparator:
<langsyntaxhighlight lang="java">
Files.list(Path.of("")).map(Path::toString).sorted(String.CASE_INSENSITIVE_ORDER).forEach(System.out::println);
</syntaxhighlight>
</lang>
 
=={{header|Javascript}}==
 
{{Works with|Node.js|4.3.2+}}
<langsyntaxhighlight lang="javascript">const fs = require('fs');
fs.readdir('.', (err, names) => names.sort().map( name => console.log(name) ));</langsyntaxhighlight>
 
=={{header|Jsish}}==
Line 868 ⟶ 1,220:
To emulate ''ls'', sorted, one entry per line:
 
<langsyntaxhighlight lang="javascript">puts(File.glob().sort().join('\n'));</langsyntaxhighlight>
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia"># v0.6.0
 
for e in readdir() # Current directory
Line 879 ⟶ 1,231:
# Same for...
readdir("~") # Read home directory
readdir("~/documents")</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// Version 1.2.41
 
import java.io.File
Line 899 ⟶ 1,251:
fun main(args: Array<String>) {
ls(".") // list files in current directory, say
}</langsyntaxhighlight>
 
=={{header|Ksh}}==
<syntaxhighlight lang="ksh">
#!/bin/ksh
 
# List everything in the current folder (sorted), similar to `ls`
 
# # Variables:
#
targetDir=${1:-/tmp/foo}
 
######
# main #
######
 
cd ${targetDir}
for obj in *; do
print ${obj}
done
</syntaxhighlight>
 
=={{header|LiveCode}}==
<langsyntaxhighlight LiveCodelang="livecode">set the defaultFolder to "/foo"
put the folders & the files
set the defaultFolder to "/foo/bar"
put the folders & the files</langsyntaxhighlight>
 
=={{header|Lua}}==
Using LuaFileSystem - available in LuaRocks, ULua, major Linux distro repos, etc, etc.
<langsyntaxhighlight Lualang="lua">require("lfs")
for file in lfs.dir(".") do print(file) end</langsyntaxhighlight>
 
=={{header|Mathematica}}==
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>Column[FileNames[]]</lang>
<syntaxhighlight lang="mathematica">Column[FileNames[]]</syntaxhighlight>
 
=={{header|Nanoquery}}==
<langsyntaxhighlight lang="nanoquery">import Nanoquery.IO
import sort
 
Line 924 ⟶ 1,295:
for i in range(0, len(fnames) - 1)
println fnames[i]
end</langsyntaxhighlight>
{{out}}
<pre>.\nanoquery-2.3_1866
Line 933 ⟶ 1,304:
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">from algorithm import sorted
<lang Nim>
from algorithm import sorted
from os import walkPattern
from sequtils import toSeq
 
for path in toSeq(walkPattern("*")).sorted:
echo path</syntaxhighlight>
</lang>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
class Test {
function : Main(args : String[]) ~ Nil {
Line 956 ⟶ 1,325:
}
}
</syntaxhighlight>
</lang>
 
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">let () =
Array.iter print_endline (
Sys.readdir Sys.argv.(1) )</langsyntaxhighlight>
 
{{Output}}
Line 974 ⟶ 1,343:
=={{header|PARI/GP}}==
GP doesn't have this capability so we can either use the shell or PARI. For the latter see [[#C|C]]; for the former:
<langsyntaxhighlight lang="parigp">system("dir/b/on")</langsyntaxhighlight>
in DOS/Windows or
<langsyntaxhighlight lang="parigp">system("ls")</langsyntaxhighlight>
in *nix.
 
Line 983 ⟶ 1,352:
 
When tested via Windows XP, the names came out in sorted order (ignoring case) however in earlier systems the files would be presented in entry order. That is, if files a, c, b were saved, they would be named in that order. Then, if file c were deleted and then a file named x were added, they would be named in the order a, x, b. In this case, a scheme for saving an unknown number of names (of unknown length) would be needed so that they could be sorted. Perhaps some linked-list with an insertionsort for each added name...
<syntaxhighlight lang="pascal">
<lang Pascal>
Program ls; {To list the names of all files/directories in the current directory.}
Uses DOS;
Line 995 ⟶ 1,364:
end;
END.
</syntaxhighlight>
</lang>
 
=={{header|Perl}}==
 
<langsyntaxhighlight lang="perl">opendir my $handle, '.' or die "Couldnt open current directory: $!";
while (readdir $handle) {
print "$_\n";
}
closedir $handle;</langsyntaxhighlight>
 
Alternatively, using <tt>glob</tt>:
<langsyntaxhighlight lang="perl">print "$_\n" for glob '*';</langsyntaxhighlight>
 
<langsyntaxhighlight lang="perl">print "$_\n" for glob '* .*'; # If you want to include dot files</langsyntaxhighlight>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">-->
<lang Phix>pp(dir("."),{pp_Nest,1,pp_IntCh,false})</lang>
<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: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">dir</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"."</span><span style="color: #0000FF;">),{</span><span style="color: #004600;">pp_Nest</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #004600;">pp_IntCh</span><span style="color: #0000FF;">,</span><span style="color: #004600;">false</span><span style="color: #0000FF;">})</span>
<!--</syntaxhighlight>-->
{{Out}}
<pre>
Line 1,027 ⟶ 1,399:
 
=== just names ===
<!--<syntaxhighlight lang="phix">-->
<lang Phix>?vslice(dir("."),D_NAME)</lang>
<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: #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: #008000;">"."</span><span style="color: #0000FF;">),</span><span style="color: #004600;">D_NAME</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{Out}}
<pre>
Line 1,034 ⟶ 1,409:
 
===prettier output===
Each element of dir() can be indexed with D_NAME, D_ATTRIBUTES, D_SIZE, D_YEAR, D_MONTH, D_DAY, D_HOUR, D_MINUTE, and D_SECOND, and of course you can easily format these things a bit nicer. Of course there is no way to get a proper directory listing in javascript, so for pwa/p2js we'll just create some fake results.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phi>include builtins\timedate.e
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
set_timedate_formats({"hh:mmpm Ddd Mmm ddth YYYY"})
<span style="color: #008080;">function</span> <span style="color: #000000;">dirf</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">path</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">date_type</span><span style="color: #0000FF;">=</span><span style="color: #004600;">D_MODIFICATION</span><span style="color: #0000FF;">)</span>
object d = dir(".")
<span style="color: #008080;">if</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()=</span><span style="color: #004600;">JS</span> <span style="color: #008080;">then</span>
if d!=-1 then
<span style="color: #008080;">return</span> <span style="color: #0000FF;">{{</span><span style="color: #008000;">`.`</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">`d`</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2022</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">11</span><span style="color: #0000FF;">,</span><span style="color: #000000;">01</span><span style="color: #0000FF;">,</span><span style="color: #000000;">09</span><span style="color: #0000FF;">,</span><span style="color: #000000;">13</span><span style="color: #0000FF;">},</span>
printf(1,"%-20s %s %10s %s\n",{"-- name --","attr","size","-- time and date --"})
<span style="color: #0000FF;">{</span><span style="color: #008000;">`..`</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">`d`</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2022</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">11</span><span style="color: #0000FF;">,</span><span style="color: #000000;">01</span><span style="color: #0000FF;">,</span><span style="color: #000000;">09</span><span style="color: #0000FF;">,</span><span style="color: #000000;">13</span><span style="color: #0000FF;">},</span>
for i=1 to length(d) do
<span style="color: #0000FF;">{</span><span style="color: #008000;">`.fake`</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">`a`</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2021</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6</span><span style="color: #0000FF;">,</span><span style="color: #000000;">42</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6</span><span style="color: #0000FF;">},</span>
printf(1,"%-20s %=4s %10s %s\n",{d[i][D_NAME],d[i][D_ATTRIBUTES],file_size_k(d[i][D_SIZE]),format_timedate(d[i][D_YEAR..$])})
<span style="color: #0000FF;">{</span><span style="color: #008000;">`directory`</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">`a`</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">18898</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2020</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span><span style="color: #000000;">13</span><span style="color: #0000FF;">,</span><span style="color: #000000;">57</span><span style="color: #0000FF;">,</span><span style="color: #000000;">37</span><span style="color: #0000FF;">},</span>
end for
<span style="color: #0000FF;">{</span><span style="color: #008000;">`for.p2js`</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">`a`</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1024</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2019</span><span style="color: #0000FF;">,</span><span style="color: #000000;">7</span><span style="color: #0000FF;">,</span><span style="color: #000000;">28</span><span style="color: #0000FF;">,</span><span style="color: #000000;">15</span><span style="color: #0000FF;">,</span><span style="color: #000000;">30</span><span style="color: #0000FF;">,</span><span style="color: #000000;">45</span><span style="color: #0000FF;">}}</span>
end if</lang>
<span style="color: #008080;">else</span>
<span style="color: #008080;">return</span> <span style="color: #7060A8;">dir</span><span style="color: #0000FF;">(</span><span style="color: #000000;">path</span><span style="color: #0000FF;">,</span><span style="color: #000000;">date_type</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins</span><span style="color: #0000FF;">\</span><span style="color: #004080;">timedate</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #7060A8;">set_timedate_formats</span><span style="color: #0000FF;">({</span><span style="color: #008000;">"hh:mmpm Ddd Mmm ddth YYYY"</span><span style="color: #0000FF;">})</span>
<span style="color: #004080;">object</span> <span style="color: #000000;">d</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">dirf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"."</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">d</span><span style="color: #0000FF;">!=-</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
<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;">"%-20s %s %10s %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #008000;">"-- name --"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"attr"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"size"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"-- time and date --"</span><span style="color: #0000FF;">})</span>
<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;">d</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">di</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">d</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">name</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">di</span><span style="color: #0000FF;">[</span><span style="color: #004600;">D_NAME</span><span style="color: #0000FF;">],</span>
<span style="color: #000000;">attr</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">di</span><span style="color: #0000FF;">[</span><span style="color: #004600;">D_ATTRIBUTES</span><span style="color: #0000FF;">],</span>
<span style="color: #000000;">size</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">file_size_k</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">][</span><span style="color: #004600;">D_SIZE</span><span style="color: #0000FF;">]),</span>
<span style="color: #000000;">tdte</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">format_timedate</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">][</span><span style="color: #004600;">D_YEAR</span><span style="color: #0000FF;">..$])</span>
<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;">"%-20s %=4s %10s %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">name</span><span style="color: #0000FF;">,</span><span style="color: #000000;">attr</span><span style="color: #0000FF;">,</span><span style="color: #000000;">size</span><span style="color: #0000FF;">,</span><span style="color: #000000;">tdte</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;">if</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 1,057 ⟶ 1,452:
animation.svg a 900 12:49pm Sat May 25th 2019
...etc
</pre>
or under pwa/p2js:
<pre>
-- name --           attr       size  -- time and date --
.                     d            0  01:09am Fri Feb 11th 2022
..                    d            0  01:09am Fri Feb 11th 2022
.fake                 a            5  06:42am Tue Jun 01st 2021
directory             a      18.46KB  01:57pm Sat Apr 04th 2020
for.p2js              a          1KB  03:30pm Sun Jul 28th 2019
</pre>
 
Line 1,063 ⟶ 1,467:
This will output all the filenames in the current directory.
 
<langsyntaxhighlight lang="php">
<?php
foreach(scandir('.') as $fileName){
echo $fileName."\n";
}
</syntaxhighlight>
</lang>
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">import os, util.
main =>
println(ls()),
println(ls("foo/bar")).
 
ls() = ls(".").
ls(Path) = [F : F in listdir(Path), F != ".",F != ".."].sort.join('\n').</syntaxhighlight>
 
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(for F (sort (dir))
(prinl F) )</langsyntaxhighlight>
 
=={{header|Pike}}==
<langsyntaxhighlight Pikelang="pike">foreach(sort(get_dir()), string file)
write(file +"\n");</langsyntaxhighlight>
 
=={{header|PowerShell}}==
<langsyntaxhighlight PowerShelllang="powershell"># Prints Name, Length, Mode, and LastWriteTime
Get-ChildItem | Sort-Object Name | Write-Output
 
# Prints only the name of each file in the directory
Get-ChildItem | Sort-Object Name | ForEach-Object Name | Write-Output</langsyntaxhighlight>
 
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">NewList lslist.s()
 
If OpenConsole("ls-sim")
If ExamineDirectory(0,GetCurrentDirectory(),"*.*")
While NextDirectoryEntry(0)
AddElement(lslist()) : lslist()=DirectoryEntryName(0)
Wend
FinishDirectory(0)
SortList(lslist(),#PB_Sort_Ascending)
ForEach lslist()
PrintN(lslist())
Next
EndIf
Input()
EndIf</syntaxhighlight>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">>>> import os
>>> print('\n'.join(sorted(os.listdir('.'))))
DLLs
Line 1,101 ⟶ 1,532:
pythonw.exe
tcl
>>> </langsyntaxhighlight>
 
=={{header|R}}==
<langsyntaxhighlight lang="rsplus">
cat(paste(list.files(), collapse = "\n"), "\n")
cat(paste(list.files("bar"), collapse = "\n"), "\n")
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,121 ⟶ 1,552:
Ooh... warning... if you run the <code>test</code> module (either with DrRacket with the test module automatically running, or with <code>raco test ls.rkt</code>, then the example directory tree is built but not torn down.
 
<langsyntaxhighlight lang="racket">#lang racket/base
 
;; Racket's `directory-list' produces a sorted list of files
Line 1,140 ⟶ 1,571:
(parameterize ([current-directory dir]) (with-output-to-string ls)))
(test (ls/str "foo") => "bar\n"
(ls/str "foo/bar") => "1\n2\na\nb\n"))</langsyntaxhighlight>
 
Both tests pass.
Line 1,149 ⟶ 1,580:
There is a <tt>dir</tt> builtin command which returns a list of IO::Path objects. We stringify them all with a hyperoperator before sorting the strings.
 
<syntaxhighlight lang="raku" perl6line>.say for sort ~«dir</langsyntaxhighlight>
 
=={{header|REXX}}==
The following program works under Windows and useduses the Windows &nbsp; '''DIR''' &nbsp; command to list a bare-bonesbare─bones sorted list.
 
<lang rexx>/*REXX program lists contents of current folder (ala mode UNIX's LS). */
'DIR /b /oN' /*use Windows DIR: sorts & lists.*/
/*stick a fork in it, we're done.*/</lang>
Notes on the options used for the &nbsp; (Microsoft Windows&reg;) &nbsp; '''DIR''' &nbsp; command:
::::* &nbsp; '''b''' &nbsp; is for <u>'''b'''</u>are format (no heading information or summary).
::::* &nbsp; '''o''' &nbsp; is for <u>'''o'''</u>rder, and it orders (sorts alphabetically) by file <u>'''N'''</u>ame.
<syntaxhighlight lang="rexx">/*REXX program lists contents of current folder (ala mode UNIX's LS). */
'DIR /b /oN' /*use Windows DIR: sorts & lists.*/
/*stick a fork in it, we're done.*/</syntaxhighlight>
{{out|output|text=''':'''}}
<pre>
1
2
3
4
</pre>
 
=={{header|RPL}}==
<code>VARS</code> returns all the files and folders in the current directory, but not sorted.
A few additional words are then needed to turn names into strings, sort the strings and come back to names.
≪ VARS LIST→ → len
≪ 1 len '''FOR''' n →STR len ROLL '''NEXT'''
len 1 '''FOR''' n
1 n 1 - '''START'''
'''IF''' DUP2 > '''THEN''' SWAP '''END''' n ROLLD '''NEXT'''
n ROLLD -1 STEP
1 len '''FOR''' n STR→ len ROLL '''NEXT'''
len →LIST
≫ ≫ ‘'''LS'''’ STO
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">
Dir.foreach("./"){|n| puts n}
</syntaxhighlight>
</lang>
This will output all files including hidden ones e.g. '.' and '..'.
 
=={{header|Run BASIC}}==
<langsyntaxhighlight Runbasiclang="runbasic">files #f, DefaultDir$ + "\*.*" ' RunBasic Default directory.. Can be any directroy
print "rowcount: ";#f ROWCOUNT() ' how many rows in directory
#f DATEFORMAT("mm/dd/yy") 'set format of file date or not
Line 1,179 ⟶ 1,631:
print "time: ";#f TIME$() ' time
print "isdir: ";#f ISDIR() ' 1 = is a directory
next</langsyntaxhighlight>
This will output RunBasics Default Directory.. It can be any directory
<pre>rowcount: 30
Line 1,197 ⟶ 1,649:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">use std::{env, fmt, fs, process};
use std::io::{self, Write};
use std::path::Path;
Line 1,220 ⟶ 1,672:
writeln!(&mut io::stderr(), "{}", msg).expect("Could not write to stderr");
process::exit(code)
}</langsyntaxhighlight>
 
{{out}}
Line 1,241 ⟶ 1,693:
 
=={{header|S-lang}}==
<langsyntaxhighlight Slang="s-lang">variable d = listdir(getcwd()), p;
foreach p (array_sort(d))
() = printf("%s\n", d[p] );</langsyntaxhighlight>
 
=={{header|Scala}}==
Line 1,275 ⟶ 1,727:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "osfiles.s7i";
 
Line 1,285 ⟶ 1,737:
writeln(name);
end for;
end func;</langsyntaxhighlight>
 
=={{header|Sidef}}==
Explicit, by opening the current working directory:
<langsyntaxhighlight lang="ruby">var content = [];
Dir.cwd.open.each { |file|
file ~~ < . .. > && next;
Line 1,297 ⟶ 1,749:
content.sort.each { |file|
say file;
}</langsyntaxhighlight>
 
Implicit, by using the <i>String.glob</i> method:
<langsyntaxhighlight lang="ruby">'*'.glob.each { |file|
say file;
}</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
cheating solution:
{{works with|Smalltalk/X}}
<langsyntaxhighlight lang="smalltalk">Stdout printCR: ( PipeStream outputFromCommand:'ls' )</langsyntaxhighlight>
real solution:
{{works with|Smalltalk/X}}
<langsyntaxhighlight lang="smalltalk">Stdout printCR:('.' asFilename directoryContents sort asStringWith:Character cr)</langsyntaxhighlight>or:<syntaxhighlight lang ="smalltalk">'.' asFilename directoryContents sort do:#printCR</langsyntaxhighlight>
full 'ls -l' output:
{{works with|Smalltalk/X}}
<langsyntaxhighlight lang="smalltalk">dir := '.' asFilename.
dir directoryContentsAsFilenames sort do:[:fn |
|line|
Line 1,346 ⟶ 1,798:
].
line printCR
].</langsyntaxhighlight>
{{out}}
<pre>-rw-r--r-- xxxxx staff 18436 13 Okt 14:16 .DS_Store
Line 1,356 ⟶ 1,808:
 
=={{header|Standard ML}}==
<langsyntaxhighlight lang="sml">OS.Process.system "ls -a" </langsyntaxhighlight>
Doing it all by yourself:
<langsyntaxhighlight lang="sml">
local (* make a sort function *)
val rec insert = fn s :string =>fn [] => [s]
Line 1,374 ⟶ 1,826:
 
sort result;
</syntaxhighlight>
</lang>
 
=={{header|Stata}}==
Stata has a builtin '''[http://www.stata.com/help.cgi?dir dir]''' command (or equivalently '''ls''').
 
<langsyntaxhighlight lang="stata">. dir *.dta
6.3k 6/12/17 14:26 auto.dta
2.3k 8/10/17 7:34 titanium.dta
6.0k 8/12/17 9:28 trend.dta</langsyntaxhighlight>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">puts [join [lsort [glob -nocomplain *]] "\n"]</langsyntaxhighlight>
 
=={{header|UNIX Shell}}==
 
Using `ls` explicitly would be a cheat, since the goal of the task is to emulate this program.
 
A simple way to list files in the current directory without using `ls` is to
use filename expansion (a.k.a. "globbing").
 
<syntaxhighlight lang="bash">echo *</syntaxhighlight>
 
To print each filename on a separate line, use a loop:
 
<syntaxhighlight lang="bash">for f in *; do echo "$f"; done</syntaxhighlight>
 
If you want this output sorted, then use `sort`:
 
<syntaxhighlight lang="bash">for f in *; do echo "$f"; done |sort</syntaxhighlight>
 
An other possibility is to use GNU coreutils' `stat`:
 
<syntaxhighlight lang="bash">stat -c %n * |sort</syntaxhighlight>
 
=={{header|Ursa}}==
<langsyntaxhighlight lang="ursa">decl file f
decl string<> fnames
set fnames (sort (f.listdir "."))
Line 1,394 ⟶ 1,867:
for (decl int i) (< i (size fnames)) (inc i)
out fnames<i> endl console
end for</langsyntaxhighlight>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">import os
 
fn main() {
contents := os.ls('.')?
println(contents)
}</syntaxhighlight>
 
=={{header|Wren}}==
<langsyntaxhighlight ecmascriptlang="wren">import "io" for Directory
 
var path = "./" // or whatever
 
// Note that output is automatically sorted using this method.
Directory.list(path).each { |f| System.print(f) }</langsyntaxhighlight>
 
=={{header|XPL0}}==
Works on Raspberry Pi.
<langsyntaxhighlight XPL0lang="xpl0">string 0;
char S;
[S:= "ls";
Line 1,412 ⟶ 1,893:
bl system
}
]</langsyntaxhighlight>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">File.glob("*").sort()</langsyntaxhighlight>
Lists all files and directories in the current directory. If you only want a list of files:
<langsyntaxhighlight lang="zkl">File.glob("*",0x8).sort()</langsyntaxhighlight>
{{out}}
<pre>
Line 1,425 ⟶ 1,906:
 
The globular method recurses down through the directories. It can send results to objects, functions, methods, threads, etc, etc. To get a sorted list of all the directories under the "Src" directory:
<langsyntaxhighlight lang="zkl">File.globular("Src",*,True,0x10,List).sort().concat("\n")</langsyntaxhighlight>
{{out}}
<pre>
9,476

edits