duangu9997 2015-01-30 18:32
浏览 492
已采纳

在Golang中设置绝对文件路径

I am a package whose only role is to provide a collection of dummy data read from files.

It looks like this:

func GetArrayOfSize(n int) []int {
f, _ := os.Open("./arrays.txt")
defer f.Close()

numbers := make([]int, 0)
scanner := bufio.NewScanner(f)

for scanner.Scan() {
    s, _ := strconv.Atoi(scanner.Text())
    numbers = append(numbers, s)
}

    return numbers[0:n]
}

It works fine when I test it inside this package however whenever I call GetArrayOfSize from another package I get a runtime error:

panic: runtime error: slice bounds out of range [recovered]
    panic: runtime error: slice bounds out of range

I am guessing this error is due to the relative path: './arrays.txt. How can I fetch the absolute path of my dummy package to fix this?

Many thanks

  • 写回答

2条回答 默认 最新

  • dongtuo3530 2015-01-30 18:49
    关注

    You should check the error return from os.Open and handle it.

    You can get the absolute path to the source code directory using the go/build package:

    p, err := build.Default.Import("github.com/user/repo/dummy", "", build.FindOnly)
    if err != nil {
        // handle error
    }
    fname := filepath.Join(p.Dir, "arrays.txt")
    

    This code assumes that the GOPATH environment variable is set.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 一道python难题2
  • ¥15 一道python难题
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备