Go 语言使用 os.Getwd()
函数来获取当前工作目录。
示例代码:
package main
import (
"fmt"
"os"
)
func main() {
dir, err := os.Getwd()
if err != nil {
fmt.Println("获取工作目录失败:", err)
} else {
fmt.Println("当前工作目录为:", dir)
}
}
输出结果:
当前工作目录为: /home/user/project
如果获取当前工作目录失败,将会输出错误信息。而在 Windows 操作系统上,Getwd() 函数可能会返回 '' 分隔符,所以在需要跨平台使用路径时,最好使用 path/filepath
包来处理路径。