代码如下:
import (
"errors"
"os"
"os/exec"
"path/filepath"
"strings"
)
func GetCurrentPath() (string, error) {
file, err := exec.LookPath(os.Args[0])
if err != nil {
return "", err
}
path, err := filepath.Abs(file)
if err != nil {
return "", err
}
i := strings.LastIndex(path, "/")
if i < 0 {
i = strings.LastIndex(path, "\\")
}
if i < 0 {
return "", errors.New(`error: Can't find "/" or "\".`)
}
return string(path[0 : i+1]), nil
}
结果:
对于非 Windows 系统,以 / 作路径分隔符,对于 Windows 系统,以 \ 作路径分隔符。
有疑问加站长微信联系(非本文作者)