Unix/ls: Difference between revisions

45,319 bytes added ,  3 months ago
m
→‎{{header|Wren}}: Changed to Wren S/H
No edit summary
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(48 intermediate revisions by 27 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}}==
 
This program runs under CP/M and lists the current directory. CP/M does not return the
filenames in sorted order, so it has to do the sorting itself.
 
<syntaxhighlight lang="8080asm">dma: equ 80h
puts: equ 9h ; Write string to console
sfirst: equ 11h ; Find first matching file
snext: equ 12h ; Get next matching file
org 100h
;;; First, retrieve all filenames in current directory
;;; CP/M has function 11h (sfirst) and function 13h (snext)
;;; to return the first, and then following, files that
;;; match a wildcard.
lxi d,0 ; Amount of files
push d ; Push on stack
lxi h,fnames ; Start of area to save names
push h ; Push on stack
lxi d,fcb ; FCB that will match any file
mvi c,sfirst ; Get the first file
getnames: call 5 ; Call CP/M BDOS
inr a
jz namesdone ; FF = we have all files
dcr a ; Dir entry is at DMA+32*A
rrc ; Rotate 3 right, same as
rrc ; rotate 5 left, *32
rrc
adi dma+1 ; Add DMA offset + 1 (filename offset)
mov e,a ; Low byte of address
mvi d,0 ; High byte is 0
mvi b,8 ; Filename is 8 bytes
pop h ; Get pointer to name area
call memcpy ; Copy the name
mvi m,' ' ; Separate name and extension
inx h
mvi b,3 ; Extension is 3 bytes
call memcpy ; Copy the extension
mvi m,13 ; While we're at it, terminate
inx h ; the filename with \r\n
mvi m,10
inx h
pop d ; Get amount of files
inx d ; Increment it (we've added a file)
push d ; Put it back onto the stack
push h ; Put the name pointer on the stack too
mvi c,snext ; Go get the next file
jmp getnames
namesdone: pop h ; Terminate the file list with $
mvi m,'$' ; so it can be printed with function 9
;;; CP/M does not keep its directory in sorted order,
;;; so we need to sort the list of files ourselves.
;;; What follows is a simple insertion sort.
lxi d,1 ; DE (i) = 1
sortouter: pop h ; Get amount of files
push h
call cmpdehl ; i < length(files)?
jnc sortdone ; If not, we're done
push d ; push i; DE (j) = i
sortinner: push d ; push j
mov a,d ; j > 0?
ora e
jz sortinnerdone ; If not, inner loop is done
dcx d ; DE = j-1
call lookup ; HL = files[j-1]
push h ; push files[j-1]
inx d ; DE = j
call lookup ; HL = files[j]
pop d ; pop DE = files[j-1]
push d ; keep them across comparison
push h
call cmpentries ; A[j] >= A[j-1]?
pop h
pop d
jc sortinnerdone ; Then inner loop is done.
mvi b,12 ; Otherwise we should swap them
swaploop: ldax d ; Get byte from files[j-1]
mov c,m ; Get byte from files[j]
mov m,a ; files[j][x]=files[j-1][x]
mov a,c ; files[j-1][x]=files[j]-[x]
stax d
inx h ; Increment pointers
inx d
dcr b ; all 12 bytes done yet?
jnz swaploop ; if not, swap next byte
pop d ; DE = j
dcx d ; j = j-1
jmp sortinner
sortinnerdone: pop d ; pop j
pop d ; pop i
inx d ; i = i + 1
jmp sortouter
sortdone: pop h ; Remove file count from stack
;;; We're done sorting the list, print it.
lxi d,fnames ; Print the now sorted list of files
mvi c,puts
jmp 5
;;; Subroutine: compare entries under DE and HL
cmpentries: mvi b,12 ; Each entry has 12 relevant bytes.
cmploop: ldax d ; Get byte from entry DE
cmp m ; Compare with byte from entry HL
rnz ; If they differ, we know the ordering
inx h ; Increment both pointers
inx d
dcr b ; Decrement byte counter
jnz cmploop ; Compare next byte
ret
;;; Subroutine: look up filename entry (HL=DE*14+fnames)
lookup: push d ; Save entry number
mov h,d
mov l,e
dad h ; HL = HL' * 2
dad d ; HL = HL' * 3
dad h ; HL = HL' * 6
dad d ; HL = HL' * 7
dad h ; HL = HL' * 14
lxi d,fnames ; Offset
dad d ; Add the offset
pop d ; Restore entry number
ret
;;; Subroutine: compare DE and HL
cmpdehl: mov a,d
cmp h
rnz
mov a,e
cmp l
ret
;;; Subroutine: copy B bytes from DE to HL
memcpy: ldax d ; Get byte from source
mov m,a ; Store byte at destination
inx h ; Increment both pointers
inx d
dcr b ; Done yet?
jnz memcpy ; If not, copy next byte
ret
;;; File control block used to specify wildcard
fcb: db 0,'???????????' ; Accept any file
ds fcb+36-$ ; Pad the FCB out to 36 bytes
fnames:</syntaxhighlight>
 
=={{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 73 ⟶ 217:
Put_Line(Result.Element(I));
end loop;
end Directory_List;</langsyntaxhighlight>
 
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">record r;
file f;
text s;
Line 89 ⟶ 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 106 ⟶ 249:
exit(0)
}
</syntaxhighlight>
</lang>
 
Sample commands and output under Windows 8:
Line 139 ⟶ 282:
 
=={{header|BaCon}}==
<langsyntaxhighlight lang="freebasic">' Emulate ls
cnt% = 0
files$ = ""
Line 156 ⟶ 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 224 ⟶ 379:
return 0;
}
</syntaxhighlight>
</lang>
 
=={{header|C++}}==
{{libheader|Boost}}
<lang cpp>
#include <iostream>
#include <set>
#include <boost/filesystem.hpp>
 
namespace fs = boost::filesystem;
 
int main(void)
{
fs::path p(fs::current_path());
std::set<std::string> tree;
 
for (auto it = fs::directory_iterator(p); it != fs::directory_iterator(); ++it)
tree.insert(it->path().filename().native());
 
for (auto entry : tree)
std::cout << entry << '\n';
}
</lang>
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.IO;
Line 272 ⟶ 406:
}
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
{{libheader|Boost}}
<syntaxhighlight lang="cpp">
#include <iostream>
#include <set>
#include <boost/filesystem.hpp>
 
namespace fs = boost::filesystem;
 
int main(void)
{
fs::path p(fs::current_path());
std::set<std::string> tree;
 
for (auto it = fs::directory_iterator(p); it != fs::directory_iterator(); ++it)
tree.insert(it->path().filename().native());
 
for (auto entry : tree)
std::cout << entry << '\n';
}
</syntaxhighlight>
 
=={{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 285 ⟶ 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 296 ⟶ 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 325 ⟶ 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 338 ⟶ 548:
a
b
:ok</langsyntaxhighlight>
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">
1> Ls = fun(Dir) ->
1> {ok, DirContents} = file:list_dir(Dir),
Line 356 ⟶ 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 366 ⟶ 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 377 ⟶ 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 396 ⟶ 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 416 ⟶ 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 432 ⟶ 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 438 ⟶ 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 464 ⟶ 694:
$
</pre>
 
=={{header|Furor}}==
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="furor">
###sysinclude dir.uh
###sysinclude stringextra.uh
 
###define COLORS
// delete the COLORS directive above if you do not want colored output!
{ „vonal” __usebigbossnamespace myself "-" 90 makestring() }
{ „points” __usebigbossnamespace myself "." 60 makestring() }
#g argc 3 < { "." }{ 2 argv } sto mypath
@mypath 'd !istrue { ."The give directory doesn't exist! Exited.\n" end }
@mypath getdir { ."Cannot load the dir! Aborted.\n" end } sto mydir
 
@mydir ~d {
."Directories:\n"
@mydir ~d {| #s
@mydir 'd {} octalrights dup print free SPACE
@mydir 'd {} getfilename dup 37 stub print SPACE drop
@mydir 'd {} groupname ': !+
@mydir 'd {} ownername dup sto temp + dup 10 stub print free @temp free
@mydir 'd {} mtime dup print free
NL |}
@points sprint
@mydir ~d { ."Total: " @mydir ~d #g print ." subdirectories.\n" }
@vonal sprint
}
@mydir ~r {
."Regular files:\n"
@mydir ~r {| #s
@mydir 'r {} octalrights dup print free SPACE
@mydir 'r {} getfilesize sbr §ifcolored
@mydir 'r {} executable { ." >" }{ ." " } SPACE
@mydir 'r {} getfilename dup 37 stub print SPACE drop
@mydir 'r {} groupname ': !+
@mydir 'r {} ownername dup sto temp + dup 10 stub print free @temp free
@mydir 'r {} mtime dup print free
NL |}
@points sprint
@mydir ~r { ."Total: " @mydir ~r #g print ." regular files. "
."TotalSize = " @mydir 'r totalsize sbr §ifcolored NL
}
@vonal sprint
}
@mydir ~L {
."Symlinks:\n"
@mydir ~L {| #s
@mydir 'L {} octalrights dup print free SPACE
@mydir 'L {} executable { .">" }{ SPACE } SPACE
@mydir 'L {} getfilename dup 67 stub print SPACE drop
@mydir 'L {} broken { ."--->" }{ ."===>" } SPACE
@mydir 'L {} destination dup 30 stub print drop
NL |}
@points sprint
@mydir ~L { ."Total: " @mydir ~L #g print ." symlinks.\n"
}
}
@vonal sprint
."Size, alltogether = " @mydir alltotal sbr §ifcolored NL
@vonal sprint
@mydir free
."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
end
 
ifcolored:
###ifdef COLORS
coloredsize
###endif
###ifndef COLORS
#g !(#s) 21 >|
###endif
dup sprint free
rts
 
{ „filsize” }
{ „mydir” }
{ „mypath” }
{ „temp” }
{ „makestring” #s * dup 10 !+ swap free #g = }
</syntaxhighlight>
 
{{out}}
An example output:
 
<pre>
Directories:
0775 arrays vz:vz 2020.05.08 15:00:34 P
0775 Brainfukk vz:vz 2020.03.28 16:06:37 Szo
0775 examples vz:vz 2020.06.07 19:26:48 V
0775 furorfonts vz:vz 2020.05.09 10:46:19 Szo
0775 furorheaders vz:vz 2020.06.02 00:37:36 K
0775 hasznosvolt vz:vz 2020.05.09 15:19:09 Szo
0775 headers vz:vz 2020.05.30 19:20:18 Szo
0775 kiserleti vz:vz 2020.05.13 19:24:23 Sze
0775 libraries vz:vz 2020.06.07 19:25:25 V
0775 OLD vz:vz 2020.06.07 23:29:10 V
0775 tests vz:vz 2020.03.16 23:00:47 H
0775 useful vz:vz 2020.06.07 23:24:42 V
............................................................
Total: 12 subdirectories.
------------------------------------------------------------------------------------------
Regular files:
0664 3313 __furor.c vz:vz 2020.05.23 14:30:17 Szo
0664 871113 A_Furor_programozasi_nyelv.odt vz:vz 2020.06.07 23:24:25 V
0664 9046 castingoperators.c vz:vz 2020.04.28 16:05:35 K
0664 32414 cmpoperators.c vz:vz 2020.06.06 18:23:20 Szo
0664 2424 dir.upu vz:vz 2020.06.09 09:47:00 K
0664 1187 eca.upu vz:vz 2020.06.07 23:13:06 V
0664 2630 fonttest.upu vz:vz 2020.05.24 23:43:48 V
0775 10756 > furor vz:vz 2020.06.07 19:25:25 V
0664 81 furordescriptorlength.upu vz:vz 2020.06.07 19:26:19 V
0664 85399 furorrun.c vz:vz 2020.06.07 19:25:12 V
0664 509 furt.upu vz:vz 2020.06.02 00:31:17 K
0664 13150 jumpingtable.c vz:vz 2020.06.06 20:58:26 Szo
0644 563834 Kajjam700.png vz:vz 2013.07.31 01:38:01 Sze
0664 21392 keywords.c vz:vz 2020.06.07 19:23:58 V
0664 5399 labelledloops.c vz:vz 2020.05.28 09:43:50 Cs
0664 2040 langtonsant.upu vz:vz 2020.05.25 15:25:41 H
0664 2581 libraries.sh vz:vz 2020.06.02 00:28:27 K
0664 84 link.txt vz:vz 2020.06.02 00:56:22 K
0664 41 lowercasealphabet.upu vz:vz 2020.06.05 22:40:34 P
0664 1035 Makefile vz:vz 2020.04.09 22:24:12 Cs
0664 1646 makeup.c vz:vz 2020.06.01 20:09:30 H
0664 884 mandelbrot9.upu vz:vz 2020.06.06 18:06:48 Szo
0664 22767 maze.upu vz:vz 2020.05.04 18:26:14 H
0664 669 myxmodmap.fur vz:vz 2020.05.11 18:51:59 H
0664 240 neglect.upu vz:vz 2020.05.16 19:33:13 Szo
0644 131072 pibinary.bin vz:vz 2018.06.07 22:36:54 Cs
0664 1270 pngxproba.upu vz:vz 2020.05.09 20:08:50 Szo
0664 1275 pngxproba2.upu vz:vz 2020.05.06 21:15:24 Sze
0644 504 preinitpostmortem.c vz:vz 2020.03.26 13:03:12 Cs
0644 5891695 primszamok.txt vz:vz 2017.01.23 18:33:14 H
0664 954 statusbar.upu vz:vz 2020.06.08 21:11:06 H
0664 3447 t.txt vz:vz 2020.06.08 22:00:05 H
0644 7401 UPU.syntax vz:vz 2020.05.25 22:34:33 H
0664 2000 verify.upu vz:vz 2020.04.29 21:10:02 Sze
0664 188 windowsresolutions.upu vz:vz 2020.06.02 00:36:08 K
0664 816 xproba.upu vz:vz 2020.05.11 11:39:39 H
0664 931 xprobafur.upu vz:vz 2020.05.11 18:49:16 H
............................................................
Total: 37 regular files. TotalSize = 7696187
------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------
Size, alltogether = 7745339
------------------------------------------------------------------------------------------
Free spaces: /* Total size of the filesystem is : 126693117952 */
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>
 
It is not visible on the output above, but the digits in the filesize are colored, each 3 digits has different color.
 
=={{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 482 ⟶ 1,018:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 505 ⟶ 1,041:
fmt.Println(n)
}
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
Line 511 ⟶ 1,047:
{{Works with|GHC|7.8.3}}
 
<langsyntaxhighlight lang="haskell">import Control.Monad
import Data.List
import System.Directory
Line 519 ⟶ 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 542 ⟶ 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 568 ⟶ 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 579 ⟶ 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 599 ⟶ 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">mportimport Nanoquery.IO
import sort
 
Line 624 ⟶ 1,295:
for i in range(0, len(fnames) - 1)
println fnames[i]
end</langsyntaxhighlight>
{{out}}
<pre>.\nanoquery-2.3_1866
<pre>.\nanoquery-2.3_1866 .\notes.txt .\nq.bat .\nq.vim .\rosetta-code</pre>
.\notes.txt
.\nq.bat
.\nq.vim
.\rosetta-code</pre>
 
=={{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 652 ⟶ 1,325:
}
}
</syntaxhighlight>
</lang>
 
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">let () =
Array.iter print_endline (
Sys.readdir Sys.argv.(1) )</langsyntaxhighlight>
 
{{Output}}
Line 670 ⟶ 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 679 ⟶ 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 691 ⟶ 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|Perl 6}}==
 
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.
 
<lang perl6>.say for sort ~«dir</lang>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">-->
<lang Phix>pp(dir("."),{pp_Nest,1})</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>
{{"`."`, "`d"`, 0,20172020,46,311,2113,025,713},
{"`.."`, "`d"`, 0,20172020,46,311,2113,025,713},
{"`.hg"`, "`d"`, 0,20172020,34,274,136,53'5'42,38'&'6},
{"`.hgignore"`, "`a"`, 1533018898,20172020,34,274,13,2957,2137},
{"alice_oz`1KB.txt"zip`, "`a"`, 3369261024,20172019,37,1528,1915,1230,2445},
{"asm"`a.exe`, "d"`a`, 0133889,20172019,48,224,20,33'!'27,39'''21},
{`address.sqlite`, `a`, 12288,2018,7,20,19,44,34},
{`alice_oz.txt`, `a`, 336926,2017,3,15,19,12,24},
{`animation.svg`, `a`, 900,2019,5,25,12,49,14},
...etc
</pre>
 
=== just names ===
<!--<syntaxhighlight lang="phix">-->
<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>
{".","..",".hg",".hgignore","1KB.zip","a.exe","address.sqlite","alice_oz.txt","animation.svg",...}
</pre>
 
===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)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
<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>
-- name -- attr size -- time and date --
. d 0 01:25pm Thu Jun 11th 2020
.. d 0 01:25pm Thu Jun 11th 2020
.hg d 0 06:42am Sat Apr 04th 2020
.hgignore a 18.46KB 01:57pm Sat Apr 04th 2020
1KB.zip a 1KB 03:30pm Sun Jul 28th 2019
a.exe a 130.75KB 08:27pm Sat Aug 24th 2019
address.sqlite a 12KB 07:44pm Fri Jul 20th 2018
alice_oz.txt a 329.03KB 07:12pm Wed Mar 15th 2017
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 728 ⟶ 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 766 ⟶ 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 786 ⟶ 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 805 ⟶ 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.
 
=={{header|Raku}}==
(formerly Perl 6)
 
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" line>.say for sort ~«dir</syntaxhighlight>
 
=={{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). */
Notes on the options used for the &nbsp; (Microsoft Windows&reg;) &nbsp; '''DIR''' &nbsp; command:
'DIR /b /oN' /*use Windows DIR: sorts & lists.*/
/*stick a fork in it, we're done.*/</lang>
Notes on the options used for the '''DIR''' 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 836 ⟶ 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 854 ⟶ 1,649:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">use std::{env, fmt, fs, process};
use std::io::{self, Write};
use std::path::Path;
Line 877 ⟶ 1,672:
writeln!(&mut io::stderr(), "{}", msg).expect("Could not write to stderr");
process::exit(code)
}</langsyntaxhighlight>
 
{{out}}
Line 896 ⟶ 1,691:
b
</pre>
 
 
=={{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 931 ⟶ 1,725:
/usr
/var </pre>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "osfiles.s7i";
 
Line 942 ⟶ 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 954 ⟶ 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}}
<syntaxhighlight lang="smalltalk">Stdout printCR: ( PipeStream outputFromCommand:'ls' )</syntaxhighlight>
real solution:
{{works with|Smalltalk/X}}
<syntaxhighlight lang="smalltalk">Stdout printCR:('.' asFilename directoryContents sort asStringWith:Character cr)</syntaxhighlight>or:<syntaxhighlight lang="smalltalk">'.' asFilename directoryContents sort do:#printCR</syntaxhighlight>
full 'ls -l' output:
{{works with|Smalltalk/X}}
<syntaxhighlight lang="smalltalk">dir := '.' asFilename.
dir directoryContentsAsFilenames sort do:[:fn |
|line|
"
generate a line of the form of ls -l:
drwxrwxrwx user group size date time name
where year is printed if not current, time of day otherwise
"
line := String streamContents:[:s |
|accessRights|
 
s nextPut:(fn isDirectory ifTrue:[$d] ifFalse:[$-]).
accessRights := fn symbolicAccessRights.
#( readUser writeUser executeUser
readGroup writeGroup executeGroup
readOthers writeOthers executeOthers
)
with:'rwxrwxrwx'
do:[:eachRight :charToPrint |
s nextPut:((accessRights includes:eachRight) ifTrue:[charToPrint] ifFalse:[$-])
].
(OperatingSystem getUserNameFromID:fn info uid) printOn:s leftPaddedTo:10.
(OperatingSystem getGroupNameFromID:fn info gid) printOn:s leftPaddedTo:10.
fn fileSize printOn:s leftPaddedTo:12.
fn modificationTime year = Date today year ifTrue:[
fn modificationTime printOn:s format:' %(dayPadded) %(ShortMonthName) %h:%m'.
] ifFalse:[
fn modificationTime asDate printOn:s format:' %(dayPadded) %(ShortMonthName) %y'.
].
s space.
s nextPutAll:fn baseName
].
line printCR
].</syntaxhighlight>
{{out}}
<pre>-rw-r--r-- xxxxx staff 18436 13 Okt 14:16 .DS_Store
-rw-r--r-- xxxxx staff 712 13 Aug 12:58 .cvsignore
...
-rwxr--r-- xxxxx staff 1440 22 Dez 14:33 script.st
-rwxr-xr-x xxxxx staff 14716 22 Dez 03:35 stx
...</pre>
 
=={{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 980 ⟶ 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,000 ⟶ 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}}==
<syntaxhighlight lang="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) }</syntaxhighlight>
 
=={{header|XPL0}}==
Works on Raspberry Pi.
<syntaxhighlight lang="xpl0">string 0;
char S;
[S:= "ls";
asm { ldr r0, S
bl system
}
]</syntaxhighlight>
 
=={{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,013 ⟶ 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