How to read names of all files and folders in current directory?


Readdirnames reads and returns a slice of names from the directory X. The names contains both name of directories and files.
file, err := os.Open(".") // reads the current directory

Example

package main

import (
	"log"
	"os"
	"fmt"
)
func readCurrentDir() {
	file, err := os.Open(".")
	if err != nil {
		log.Fatalf("failed opening directory: %s", err)
	}
	defer file.Close()

	list,_ := file.Readdirnames(0) // 0 to read all files and folders
	for _, name := range list {
		fmt.Println(name)
	}
}

func main() {
	readCurrentDir()
}

Output

Books
example
example1.go
example10.go
example11.go
example12.go
example13.go
example14.go
example15.go
example16.GO
example17.go
example19.go
example2.go
example20.go
example3.go
example6.go
example7.go
example8.go
example9.go
input.txt
test.txt
text.txt
Most Helpful This Week