如何使用Go从stdin上指定的目录中读取文件名

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:

  1. Request directory from user using bufio library
  2. Determine absolute path based on common path abbreviations using os library
  3. Read directory contents using ioutil library
  4. Print absolute path; iterate through directory contents and print name of each item


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())
    }
}