Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

golang os 模块 #9

Open
AlexZ33 opened this issue May 25, 2021 · 0 comments
Open

golang os 模块 #9

AlexZ33 opened this issue May 25, 2021 · 0 comments

Comments

@AlexZ33
Copy link
Member

AlexZ33 commented May 25, 2021

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 系统下默认是“\”,写在代码中时要用“\”或“/”代替。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant