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

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

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

zqnj2004 回答:无法使用os.Chdir()更改目录

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

这是代码的一个最小的,可复制的示例,丢弃了除基本代码以外的所有代码,并打印输入,输出和错误。

onClick

输出:

Windows:

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())
}

Linux:

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

有效。

运行它并将其与您的代码进行比较。

本文链接:https://www.f2er.com/2834741.html

大家都在问