I would like to read all files from a given directory, and I tried this:
package main
import (
"bufio"
"fmt"
"io/ioutil"
"os"
"strings"
)
func main() {
fmt.Print("directory: ")
inBuf := bufio.NewReader(os.Stdin)
inDir, _ := inBuf.ReadString('
')
strings.Replace(inDir, "\\", "/", -1)
files, _ := ioutil.ReadDir(inDir)
fmt.Println(files)
}
This will always return "[]" with or without the "strings.Replace" line. Could anyone point out the problem with the code, or provide a easier way to accomplish this task? Thanks!
It isn't working because you must strip the from the inDir variable, otherwise it tries to list the contents of "dirprovided ". Something like this might work:
func main() {
fmt.Print("directory: ")
inBuf := bufio.NewReader(os.Stdin)
inDir, _ := inBuf.ReadString('
')
inDir = strings.Replace(inDir, "
", "", -1)
files, _ := ioutil.ReadDir(inDir)
fmt.Println(files)
}
Edit: also as mentioned above, printing the errors instead of dropping will help. That's all I did to figure this one out.
Suggested steps:
package main
import (
"bufio"
"fmt"
"io/ioutil"
"os"
)
func main() {
// STEP ONE
scanner := bufio.NewScanner(os.Stdin)
fmt.Print("Choose a directory: ")
scanner.Scan()
dir := scanner.Text()
// STEP TWO
if dir[:1] == "~" {
dir = os.Getenv("HOME") + dir[1:]
} else if dir[:1] != "/" {
pwd, _ := os.Getwd()
dir = pwd + "/" + dir
}
// STEP THREE
files, _ := ioutil.ReadDir(dir)
// STEP FOUR
fmt.Println("Directory: ", dir, "
")
for _, f := range files {
fmt.Println(f.Name())
}
}