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
Send and Receive values from Channel
Example: How to use ReadFull from IO Package in Golang?
Example: ReadAll, ReadDir, and ReadFile from IO Package
Struct Instantiation Using Pointer Address Operator
How do you handle HTTP server health checks in Go?
Defining a type that satisfies an interface in Go Programming Language