C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Readdir: This is an important step—we must call Readdir. The argument 0 is acceptable—this means no options are applied in the operation.
For: We use a for-range loop to iterate over all the files. We call the Name() func to get each file's name.
ForrangeFinally: We can get the full path for each file by using the directory we are reading from, and prepending that to the file's name.
Golang program that uses Readdir
package main
import (
"fmt"
"os"
)
func main() {
// Directory we want to get all files from.
directory := "/home/sam/";
// Open the directory.
outputDirRead, _ := os.Open(directory)
// Call Readdir to get all files.
outputDirFiles, _ := outputDirRead.Readdir(0)
// Loop over files.
for outputIndex := range(outputDirFiles) {
outputFileHere := outputDirFiles[outputIndex]
// Get name of file.
outputNameHere := outputFileHere.Name()
// Print name.
fmt.Println(outputNameHere)
}
}
Output
.config
.xsession-errors.old
Downloads
.profile
Templates
coin.jpg
test.py
.xsession-errors
examples.desktop
.ICEauthority
.pki
.bash_logout
.local
.Xauthority
.bash_history
Documents
.compiz
.bashrc
Pictures
Link to firefox-bin
.sudo_as_admin_successful
.gnupg
.mozilla
test
.dbus
.cache
program.go
Videos
Public
.gconf
Desktop
Music