7
golang 获取三种不同的路径方法(执行路径,项目路径,文件路径)
source link: https://studygolang.com/articles/35054
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
golang 获取三种不同的路径方法(执行路径,项目路径,文件路径)
runningstarh · 11天之前 · 334 次点击 · 预计阅读时间 1 分钟 · 大约8小时之前 开始浏览func checkErr(err error) {
if err != nil {
panic(err)
}
}
//获取当前的执行路径
//C:\Users\Vic\AppData\Local\Temp\
func getCurrentPath() string {
s, err := exec.LookPath(os.Args[0])
checkErr(err)
i := strings.LastIndex(s, "\\")
path := string(s[0 : i+1])
return path
}
//获取当前文件的详细路径
//D:/Go/workspace/port/network_learn/server/server.go
func CurrentFile() string {
_, file, _, ok := runtime.Caller(1)
if !ok {
panic(errors.New("Can not get current file info"))
}
return file
}
func main() {
//D:\Go\workspace\port
pa,_:=os.Getwd()
path:=getCurrentPath()
filePath:=CurrentFile()
fmt.Println(pa)
fmt.Println(path)
fmt.Println(filePath)
}
一、为什么写这样的一篇文章,因为我在获取当前文件的详细路径时找不到对应的方法,我将详细展示三种的源码方案
有疑问加站长微信联系(非本文作者)
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK