无法使用os.Chdir()更改目录

问题描述 投票:0回答:1

golang中的os.Chdir()无法正常工作。

package main

import (
    "fmt"
    "os"
)

func main() {
    command := "cd C:\\"
    if err := os.Chdir(command[3:]); err != nil {
        fmt.Println("Error:\tCould not move into the directory (%s)\n")
    }
}

输出:

Error:   Could not move into the directory

我是在做错什么还是错过了什么?

windows go cd chdir
1个回答
0
投票

您没有最小的可复制示例。参见:How to create a Minimal, Reproducible Example

这是您的代码的最低限度,可重现的示例,丢弃基本代码以外的所有代码,并打印输入,输出和错误。

package main

import (
    "fmt"
    "os"
    "runtime"
)

func main() {
    fmt.Println(os.Getwd())
    dir := `C:\`
    if runtime.GOOS != "windows" {
        dir = `/`
    }
    err := os.Chdir(dir)
    fmt.Println(dir, err)
    fmt.Println(os.Getwd())
}

输出:

Windows:

C:\Users\peter>go run chdir.go
C:\Users\peter <nil>
C:\ <nil>
C:\ <nil>
C:\Users\peter>

Linux:

$ go run chdir.go
/home/peter <nil>
/ <nil>
/ <nil>
$ 

有效。

现在,将其与您的代码进行比较,以了解您在哪里出错。

© www.soinside.com 2019 - 2024. All rights reserved.