Standard library / os

os.File.Readdir()

Reads FileInfo records in directory order; positive n limits records, nonpositive n reads all remaining. Example uses a disposable temporary workspace. Expected stdout: 'a.txt 3\n'.

Formal Syntax & Structure

go syntaxgo
func (f *File) Readdir(n int) ([]FileInfo, error)

Parameters & Attributes

NameTypeDescription
nintMaximum entries if positive; otherwise all remaining.

Return Value

([]FileInfo, error)

Reads FileInfo records in directory order; positive n limits records, nonpositive n reads all remaining.

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()  f, e := os.Open(".")  check(e)  defer f.Close()  d, e := f.Readdir(-1)  check(e)  fmt.Println(d[0].Name(), d[0].Size())}
Go Reference