如何使用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!
我想从给定目录中读取所有文件,我尝试这样做: p> \ n
包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)
个文件,_:= ioutil.ReadDir(inDir)
fmt.Println(文件)
}
code> pre>
这将始终返回“ []”,带有或不带有“ strings.Replace”行。 谁能指出代码中的问题,还是提供一种更简单的方法来完成此任务? 谢谢! p>
div>
答
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:
- Request directory from user using bufio library
- Determine absolute path based on common path abbreviations using os library
- Read directory contents using ioutil library
- 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())
}
}