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

在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
    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.

    点赞 评论
  • duanhuiqing9528
    duanhuiqing9528 2015-01-30 18:44

    Run the install command with the go tool and you should be able to run your command from anywhere on your system. Here's a good link that gives an example of the install command: How To Write Go Code

    点赞 评论

相关推荐