How to list the contents of a directory using the os package in Golang?

To list the contents of a directory using the os package in Go, you can use the Readdir function from the os package. Here's an example:

package main import ( "fmt" "os" ) func main() { dirPath := "/path/to/dir" // Replace with the actual directory path // Open the directory dir, err := os.Open(dirPath) if err != nil { fmt.Println("Error opening directory:", err) return } defer dir.Close() // Read the contents of the directory fileInfos, err := dir.Readdir(0) if err != nil { fmt.Println("Error reading directory contents:", err) return } // Print the names of the files and directories for _, fileInfo := range fileInfos { fmt.Println(fileInfo.Name()) } }

Make sure to replace "/path/to/dir" with the actual path of the directory you want to list the contents of. The Readdir function returns a slice of FileInfo objects that represent the files and directories in the specified directory. You can access properties of each FileInfo object, such as the name, size, and permissions. In the example above, we are only printing the names of the files and directories.