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条)

报告相同问题?