go - 不能将 bufio.ReadString{} 与 ioutil.ReadFile() 一起使用

标签 go

如果我尝试通过终端读取文件名,似乎无法找到它。但是,如果我对它进行硬编码,一切都会好起来吗?这不是写出来的问题。

这段代码:

package main

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

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

func getUserInput(message string) (text string){
    reader := bufio.NewReader(os.Stdin)
    fmt.Println(message)
    text, err := reader.ReadString('\n')
    check(err)
    return text
}

func main() {
    input := getUserInput("File to open?")
    fmt.Println(input)
    dat, err := ioutil.ReadFile(input)
    check(err)

    fmt.Print("% x \n", dat)
    input = getUserInput("File to write?")
    d1 := []byte(dat)
    e := ioutil.WriteFile(input, d1, 0644)
    check(e)
}

产量:

panic: open a.jpg
: no such file or directory

goroutine 1 [running]:
runtime.panic(0x4a36c0, 0xc21001d2a0)
    /usr/lib/go/src/pkg/runtime/panic.c:266 +0xb6
main.check(0x7fdcd2e07088, 0xc21001d2a0)
    /home/matt/Dropbox/CSE3320/fs_GO/fs.go:17 +0x4f
main.main()
    /home/matt/Dropbox/CSE3320/fs_GO/fs.go:35 +0x13e
exit status 2

还有这段代码:

package main

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

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

func getUserInput(message string) (text string){
    reader := bufio.NewReader(os.Stdin)
    fmt.Println(message)
    text, err := reader.ReadString('\n')
    check(err)
    return text
}

func main() {
        //input := getUserInput("File to open?")
        //fmt.Println(input)
    dat, err := ioutil.ReadFile("a.jpg")
    check(err)

    //fmt.Print("% x \n", dat)
    input := getUserInput("File to write?")
    d1 := []byte(dat)
    e := ioutil.WriteFile(input, d1, 0644)
    check(e)
}

Appears to work just fine

在不检查错误的情况下运行第一个代码时,会创建一个空白的新文件。然而,即使使用相同的函数编写文件以获取新文件名,第二次运行也能完美运行。

我完全不知道我在这里做错了什么。如果这有助于让我知道您还需要什么,这是我的版本信息。

go version 给我 go version go1.2.1 linux/amd64

最佳答案

问题是文件名以换行符结尾:

panic: open a.jpg
: no such file or directory

应该是:

panic: open a.jpg: no such file or directory

这是因为ReadString() (强调我的):

reads until the first occurrence of delim in the input, returning a string containing the data up to and including the delimiter.

使用 input = strings.TrimSpace(input) 删除换行符。


额外提示 1:不要使用 fmt.Println(input) 来调试,您应该使用 fmt.Printf("%#v\n", input)。这将更清楚地显示空格和不可打印的字符。

额外提示 2:Go 1.2.1 很旧;您应该考虑使用更新的版本。 Go is very compatible升级到更新版本通常不是问题。

关于go - 不能将 bufio.ReadString{} 与 ioutil.ReadFile() 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44772499/

相关文章:

go - 无法使用 Go 在函数中覆盖列表类型接口(interface) {}

struct - 在已经类型化的结构上进行 Go 结构类型

url - Golang 中包含大括号的错误请求 400

methods - 重命名类型后,我无法访问其某些方法

multithreading - 等待共享计时器的多个 go 例程导致竞争

go - 如何在 Golang 模板中打印对象,就像我们可以在 JavaScript 中完成一样

go - 如何将排序接口(interface)实现类型作为函数参数传递?

casting - Golang 转换多个返回值以匹配命名结果参数

go - 在 Goroutine 中等待管道 io.Copy 时发生死锁

go - cgo(golang): error: underfined reference to 'hello'