douzi1986 2015-08-05 21:09
浏览 9

GoLang:阅读文件基础

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('
')
    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条回答 默认 最新

  • doudang1052 2015-08-05 21:14
    关注
    f, err := reader.ReadString('
    ')
    

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

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

    评论

报告相同问题?

悬赏问题

  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)