Standard library / os
os.ReadDir()
Reads directory entries sorted by filename; can return partial results with an error. Example uses a disposable temporary workspace. Expected stdout: '0.txt\na.txt\n'.
Formal Syntax & Structure
go syntaxgo
func ReadDir(name string) ([]DirEntry, error)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| name | string | Name or pathname of the target. |
Return Value
([]DirEntry, error)
Reads directory entries sorted by filename; can return partial results with an error.
Working Example
Example Snippetgo
package main
import ( "fmt" "os")
func check(e error) { if e != nil { panic(e) }}func seed() { check(os.WriteFile("a.txt", []byte("abc"), 0600)) }func workspace() func() { root, e := os.MkdirTemp("", "bytemind-go-") check(e) old, e := os.Getwd() check(e) check(os.Chdir(root)) return func() { check(os.Chdir(old)); check(os.RemoveAll(root)) }}func main() { defer workspace()() seed() check(os.WriteFile("0.txt", nil, 0600)) d, e := os.ReadDir(".") check(e) for _, v := range d { fmt.Println(v.Name()) }}