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 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据