Skip to content

golang os 模块 #9

Description

@AlexZ33

1. os.Getwd()函数

原型:func Getwd()(pwd string, err error)

作用:获取当前文件路径

返回:当前文件路径的字符串和一个err信息

示例:

package main
import (
       "fmt"
       "os"
)
func main() {
       dir,_ := os.Getwd()
       fmt.Println("当前路径:",dir)
}

输出:

当前路径: D:\Projects\Go\mGoLab01

2. os.Getenv()函数

原型:func Getenv(key string) string

作用:获取系统环境变量的值

参数:key - 系统环境变量名

返回:系统环境变量的值

示例:

package main
import (
       "fmt"
       "os"
)
func main() {
       path := os.Getenv("GOPATH")
       fmt.Println("环境变量GOPATH的值是:",path)

}

输出:

环境变量GOPATH的值是: D:/Projects/Go

3. os.Chdir()函数

原型:func Chdir(dir string) error

作用:将当前文件路径改变为目标路径(非真实改变)

参数:dir - 目标路径(即改变之后的路径)

返回:修改成功,返回 nil;修改失败(如:目标路径不存在的情况),返回错误信息。

示例一:

func main() {
       beforeDir, _ := os.Getwd()
       fmt.Println("起始路径:",beforeDir)
       err := os.Chdir("D:\\Projects\\Go\\Demo02")  //存在的目录
       if err == nil{
              lateDir, _ := os.Getwd()
              fmt.Println("修改后的路径:",lateDir)
       }else {
              fmt.Println("error:",err)
       }
}

输出:

起始路径: D:\Projects\Go\mGoLab01

修改后的路径: D:\Projects\Go\Demo02

示例二:

func main() {
       beforeDir, _ := os.Getwd()
       fmt.Println("起始路径:",beforeDir)
       err := os.Chdir("D:\\Projects\\Go\\Demo03")   // 不存在的目录
       if err == nil{
              lateDir, _ := os.Getwd()
              fmt.Println("修改后的路径:",lateDir)
       }else {
              fmt.Println("error:",err)
       }
} 

输出:

起始路径: D:\Projects\Go\mGoLab01
error: chdir D:\Projects\Go\Demo03: The system cannot find the file specified.

注:文件路径,Window 系统下默认是“\”,写在代码中时要用“\”或“/”代替。

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions