首页 > 其他 > 详细

go中使用xcopy问题追踪

时间:2021-04-07 12:36:23      阅读:20      评论:0      收藏:0      [点我收藏+]

背景:

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

源文件夹: "C:\workspace_go\test_pb"
目标文件夹 "C:\workspace_go\fff"
os.Stat | err: CreateFile "C:\workspace_go\fff": 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\test_pb
目标文件夹 C:\workspace_go\fff
windows
cmdOut:  ???? C:\workspace_go\fff\Common.proto (Y:??/N:??/A:???)?
???? C:\workspace_go\fff\Common.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\n", 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\n", 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\n", string(outPut))
	return nil
}

  

go中使用xcopy问题追踪

原文:https://www.cnblogs.com/lurenjia1994/p/14626325.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!