Unix/ls: Difference between revisions

From Rosetta Code
Content added Content deleted
(Add Go)
Line 17: Line 17:
a
a
b</pre>
b</pre>

=={{header|Go}==
<lang Go>package main

import (
"fmt"
"io/ioutil"
"sort"
)

func main() {
info, err := ioutil.ReadDir(".")
if err != nil {
panic(err)
}

files := []string{}
for i := 0; i < len(info); i++ {
files = append(files, info[i].Name())
}
sort.Strings(files)

for i := 0; i < len(files); i++ {
fmt.Printf("%s\n", files[i])
}
}</lang>


=={{header|J}}==
=={{header|J}}==

Revision as of 17:54, 8 June 2014

Unix/ls is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

Write a program that will list everything in the current folder, similar to the Unix utility “ls[1] (or the Windows terminal command “DIR”). The output must be sorted, but printing extended details and producing multi-column output is not required.

Example output

For the list of paths:

/foo/bar
/foo/bar/1
/foo/bar/2
/foo/bar/a
/foo/bar/b

When the program is executed in `/foo`, it should print:

bar

and when the program is executed in `/foo/bar`, it should print:

1
2
a
b

{{header|Go}

<lang Go>package main

import ( "fmt" "io/ioutil" "sort" )

func main() { info, err := ioutil.ReadDir(".") if err != nil { panic(err) }

files := []string{} for i := 0; i < len(info); i++ { files = append(files, info[i].Name()) } sort.Strings(files)

for i := 0; i < len(files); i++ { fmt.Printf("%s\n", files[i]) } }</lang>

J

<lang J> >{."#.1!:0'*'</lang>

Almost half of that is removing extra detail not relevant to this task.

Perl 6

There is a dir 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>

Python

<lang python>>>> import os >>> print('\n'.join(sorted(os.listdir('.')))) DLLs Doc LICENSE.txt Lib NEWS.txt README.txt Scripts Tools include libs python.exe pythonw.exe tcl >>> </lang>

Rust

<lang rust>use std::os; use std::io::fs;

fn main() { let cwd = os::getcwd(); match fs::readdir(&cwd) { Ok(v) => { let mut filenames = Vec::new(); for entry in v.iter() { match entry.filename_str() { Some(str) => filenames.push(str), None => fail!(format!("unable to get filename of path {}", entry.display())) }; }

filenames.sort(); for filename in filenames.iter() { println!("{}", filename); } } Err(e) => fail!(e) } }</lang>

Tcl

<lang tcl>puts [join [lsort [glob -nocomplain *]] "\n"]</lang>