如何使用Go从标准输入中指定的目录中读取文件名

huangapple go评论79阅读模式
英文:

How to read file names from a directory specified on stdin with Go

问题

我想阅读给定目录中的所有文件,并尝试了以下代码:

package main

import (
	"bufio"
	"fmt"
	"io/ioutil"
	"os"
	"strings"
)

func main() {
    fmt.Print("directory: ")
	inBuf := bufio.NewReader(os.Stdin)
	inDir, _ := inBuf.ReadString('\n')
	strings.Replace(inDir, "\\", "/", -1)
	files, _ := ioutil.ReadDir(inDir)
	fmt.Println(files)
}

无论是否有strings.Replace这一行,它都会始终返回"[]"。有人能指出代码的问题,或者提供更简单的方法来完成这个任务吗?谢谢!

英文:

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('\n')
    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!

答案1

得分: 2

这是翻译好的内容:

它无法工作是因为你必须去掉inDir变量中的换行符,否则它会尝试列出"dirprovided\n"的内容。类似这样的代码可能有效:

func main() {
    fmt.Print("directory: ")
    inBuf := bufio.NewReader(os.Stdin)
    inDir, _ := inBuf.ReadString('\n')
    inDir = strings.Replace(inDir, "\n", "", -1)
    files, _ := ioutil.ReadDir(inDir)
    fmt.Println(files)
}

编辑:还有如上所述,打印错误而不是丢弃错误会有所帮助。这就是我解决这个问题所做的一切。

英文:

It isn't working because you must strip the \n from the inDir variable, otherwise it tries to list the contents of "dirprovided\n". Something like this might work:

func main() {
    fmt.Print("directory: ")
    inBuf := bufio.NewReader(os.Stdin)
    inDir, _ := inBuf.ReadString('\n')
    inDir = strings.Replace(inDir, "\n", "", -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.

答案2

得分: 0

建议的步骤:

  1. 使用 bufio 库从用户那里请求目录
  2. 使用 os 库根据常见的路径缩写确定绝对路径
  3. 使用 ioutil 库读取目录内容
  4. 打印绝对路径;遍历目录内容并打印每个项目的名称
package main

import (
	"bufio"
	"fmt"
	"io/ioutil"
	"os"
)

func main() {
	// 步骤一
	scanner := bufio.NewScanner(os.Stdin)
	fmt.Print("选择一个目录:")
	scanner.Scan()
	dir := scanner.Text()

	// 步骤二
	if dir[:1] == "~" {
		dir = os.Getenv("HOME") + dir[1:]
	} else if dir[:1] != "/" {
		pwd, _ := os.Getwd()
		dir = pwd + "/" + dir
	}

	// 步骤三
	files, _ := ioutil.ReadDir(dir)

	// 步骤四
	fmt.Println("目录:", dir, "\n")
	for _, f := range files {
		fmt.Println(f.Name())
	}
}
英文:

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

<br>

package main

import (
	&quot;bufio&quot;
	&quot;fmt&quot;
	&quot;io/ioutil&quot;
	&quot;os&quot;
)

func main() {
	// STEP ONE
	scanner := bufio.NewScanner(os.Stdin)
	fmt.Print(&quot;Choose a directory: &quot;)
	scanner.Scan()
	dir := scanner.Text()


	// STEP TWO
	if dir[:1] == &quot;~&quot; {
		dir = os.Getenv(&quot;HOME&quot;) + dir[1:]
	} else if dir[:1] != &quot;/&quot; {
		pwd, _ := os.Getwd()
		dir = pwd + &quot;/&quot; + dir
	}

	// STEP THREE
	files, _ := ioutil.ReadDir(dir)

	// STEP FOUR
	fmt.Println(&quot;Directory: &quot;, dir, &quot;\n&quot;)		
	for _, f := range files {
		fmt.Println(f.Name())
	}
}

huangapple
  • 本文由 发表于 2015年4月22日 05:41:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/29783648.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定