Listing Directory Contents in Go Without Recursion
In Go, listing files and folders within a specified directory can be accomplished by leveraging the ReadDir function from the os package. Unlike filepath.Walk, which traverses directories recursively, ReadDir limits its scope to the designated directory.
The ReadDir function returns a slice of os.DirEntry objects, which provide information about each directory entry, including filename and file type. To list the contents of a directory without delving into subdirectories, follow these steps:
package main import ( "fmt" "os" "log" ) func main() { entries, err := os.ReadDir("./") if err != nil { log.Fatal(err) } for _, e := range entries { fmt.Println(e.Name()) } }
In this example, the ReadDir function reads the current directory's contents and stores them in the entries slice. Each os.DirEntry in the slice contains the entry's name, which is then printed to the console.
This approach provides a straightforward method to list the files and folders within a specific directory without exploring subdirectories.
The above is the detailed content of How to List a Directory's Contents in Go Without Recursion?. For more information, please follow other related articles on the PHP Chinese website!