GoLang:读取文件基础知识

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

GoLang: Reading a File Basics

问题

我只会为你提供翻译服务,以下是翻译好的内容:

我只是尝试读取与实际程序位于同一目录中的一个简单文件。我一直遇到这个奇怪的错误,我的Go语言正在“崛起”(正如他们所说)。

package main

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

func check(e error) {
	if e != nil {
		panic(e)
	}
}

func main() {
	// 这里通过程序打开一个平面文件。
	// fn := " ... /foo.txt";
	here, err := filepath.Abs(".")
	check(err)

	fmt.Println("------- DEBUG -------")
	fmt.Println(here)
	fmt.Println("------- DEBUG -------")

	reader := bufio.NewReader(os.Stdin)
	fmt.Print("请输入文件名:")

	f, err := reader.ReadString('\n')
	f = filepath.Join(here, f)
	fmt.Println(f)
	check(err)

	dat, err := ioutil.ReadFile(f)
	check(err)
	fmt.Print(string(dat))
}

这是我一直遇到的奇怪错误。

panic: 打开 ... /foo.txt: 没有那个文件或目录

goroutine 1 [running]:
main.check(0x22081c49a0, 0x2081ec240)
... /read.go:13 +0x50
main.main()
... /read.go:36 +0x6b0
exit status 2

当我只使用静态名称而不是标准输入时,它可以正常工作。标准输入的方式可能有些奇怪,它会尝试将字符串转换为文件路径。

英文:

I'm just trying to read a simple file that's in the same directory as the actual program. I keep getting this odd error and my Go is "emerging" (as they say).

package main

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

func check(e error) {
    if e != nil {
	    panic(e)
    }
}

func main() {
    // Here's opening a flat file via the program.
    // fn := " ... /foo.txt"
    here, err := filepath.Abs(".")
    check(err)

    fmt.Println("------- DEBUG ------- ")
    fmt.Println(here)
    fmt.Println("------- DEBUG ------- ")

    reader := bufio.NewReader(os.Stdin)
    fmt.Print("Please Enter a File Name: ")

    f, err := reader.ReadString('\n')
    f = filepath.Join(here, f)
    fmt.Println(f)
    check(err)

    dat, err := ioutil.ReadFile(f)
    check(err)
    fmt.Print(string(dat))
}

So here's the weird error, I keep getting.

panic: open ... /foo.txt
: no such file or directory

goroutine 1 [running]:
main.check(0x22081c49a0, 0x2081ec240)
... /read.go:13 +0x50
main.main()
... /read.go:36 +0x6b0
exit status 2

When I just use the static name and not standard in, it works fine. There must be something odd with the way standard in pulls in that string and then tries to turn it into a file path.

答案1

得分: 7

f, err := reader.ReadString('\n')

这个代码读取的是包括\n在内的内容。所以你的文件名是/foo.txt\n,而这个文件并不存在。

如果你愿意,你可以使用strings.Trim()函数去掉换行符。

英文:
f, err := reader.ReadString('\n')

This reads up-to-and-including the \n. So your filename is /foo.txt\n which doesn't exist.

You can use strings.Trim() to pull off the newline if you like.

huangapple
  • 本文由 发表于 2015年8月6日 05:09:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/31842870.html
匿名

发表评论

匿名网友

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

确定