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
Cannot use <variable> (type <type>) as type <new-type> error in Golang
GO Program to find area and circumference of circle
Golang Program to print numbers with diamond pattern
Golang program for implementation of Rabin-Karp
GO supports the standard arithmetic operators: (Addition, Subtraction, Multiplication, Division,Remainder)
How To Make HTTP Requests in Go?
Golang read json file into struct
How to Convert string to integer type in Go?
Go program to reading plain text files
How to use WaitGroup to delay execution of the main function until after all goroutines are complete.