go中使用xcopy问题追踪

背景:

go中执行xcopy时,报错如下:

源文件夹: "C:workspace_go	est_pb"
目标文件夹 "C:workspace_gofff"
os.Stat | err: CreateFile "C:workspace_gofff": The filename, directory name, or volume label syntax is incorrect.

问题1:debug发现最终执行的代码中"变成了"

此处原因是因为cmd在解析命令时,会把"转义成",导致路径识别不正确,所以代码中在处理路径时,不要在前后加双引号

问题2:路径中的会导致程序运行得到:err: exit status 4

 

 具体原因不明,将替换成/可解决

问题3:xcopy文件存在时,覆盖需要输入命令确定

可加入/y参数自动确认,未加时报错如下

API server listening at: 127.0.0.1:20075
源文件夹: C:workspace_go	est_pb
目标文件夹 C:workspace_gofff
windows
cmdOut:  ���� C:workspace_gofffCommon.proto (Y:��/N:��/A:ȫ��)?
���� C:workspace_gofffCommon.proto (Y:��/N:��/A:ȫ��)?
cmd.Run() | err: exit status 2
--- FAIL: TestCopyDir (18.72s)
    --- FAIL: TestCopyDir/case1 (18.72s)
        utils_test.go:21: CopyDir() error = exit status 2, wantErr false
FAIL
Process exiting with code: 0

最终win10下可运行代码:

func CopyDir(src string, dst string) error {
	// src = fmt.Sprintf(`'%s'`, src)
	// dst = fmt.Sprintf(`'%s'`, dst)
	src = strings.Replace(src, splitor, `\`, -1) // splitor = `\`
	dst = strings.Replace(dst, splitor, `\`, -1)
	// src = strings.Replace(src, `\`, splitor, -1)
	// dst = strings.Replace(dst, `\`, splitor, -1)
	fmt.Println("源文件夹:", src)
	fmt.Println("目标文件夹", dst)

	_, err := os.Stat(dst)
	if err != nil {
		if os.IsNotExist(err) {
			os.MkdirAll(dst, os.ModePerm)
		}
		fmt.Printf("os.Stat | err: %v
", err)
	}

	var cmd *exec.Cmd
	var cmdOut bytes.Buffer
	switch runtime.GOOS {
	case "windows":
		fmt.Println("windows")
		cmd = exec.Command("xcopy", src, dst, "/I", "/E", "/-y")
		cmd.Stdout = &cmdOut
		e := cmd.Run()
		fmt.Println("cmdOut: ", cmdOut.String())
		if e != nil {
			fmt.Printf("cmd.Run() | err: %v
", e)
			return e
		}
	case "darwin", "linux":
		fmt.Println("darwin", "linux")
		cmd = exec.Command("cp", "-R", src, dst)
	}

//	outPut, e := cmd.Output()
//	if e != nil {
//		return e
//	}
//	fmt.Printf("output: %s
", string(outPut))
	return nil
}

  

Become a Linux Programmer
原文地址:https://www.cnblogs.com/lurenjia1994/p/14626325.html