删除目录及其所有子目录

huangapple go评论84阅读模式
英文:

Remove directory and all subdirectories

问题

这是我尝试的代码:

package main

import (
	"fmt"
	"os/exec"
)

func main() {
	fmt.Println("Removing build directory")
	if err := exec.Command("cmd", "/S", "/Q", "RD", "c:\\build").Run(); err != nil {
		fmt.Printf("Error removing build directory: %s\n", err)
	}

	if err := exec.Command("cmd", "/C", "mkdir", "c:\\build").Run(); err != nil {
		fmt.Printf("Error making new build directory: %s\n", err)
	}
}

我的输出是:

Removing build directory
Error making new build directory: exit status 1

所以在删除时我没有收到任何错误,但它没有删除任何内容。

为什么会这样?

英文:

This is what I tried:

package main

import (
	"fmt"
	"os/exec"
)

func main() {
	fmt.Println("Removing build directory")
	if err := exec.Command("cmd", "/S /Q", "RD", "c:\\build").Run(); err != nil {
		fmt.Printf("Error removing build directory: %s\n", err)
	}

	if err := exec.Command("cmd", "/C", "mkdir", "c:\\build").Run(); err != nil {
		fmt.Printf("Error making new build directory: %s\n", err)
	}
}

And my output is:

Removing build directory
Error making new build directory: exit status 1

So I don't get any error when removing, but it doesn't delete anything.

Why is that ?

答案1

得分: 0

试试这个..

func main() {
    fmt.Println("删除构建目录")
    
    c := exec.Command("cmd", "/C", "rd /S /Q", "C:\\build")
    
    if err := c.Run(); err != nil { 
        fmt.Println("错误: ", err)
    }  
    

    if err := exec.Command("cmd", "/C", "mkdir", "c:\\build").Run(); err != nil {
        fmt.Printf("创建新的构建目录时出错: %s\n", err)
    }
    
}
英文:

Try this..

func main() {
    fmt.Println("Removing build directory")
    
   c := exec.Command("cmd", "/C", "rd /S /Q", "C:\\build")
   
    if err := c.Run(); err != nil { 
        fmt.Println("Error: ", err)
    }  
    

    if err := exec.Command("cmd", "/C", "mkdir", "c:\\build").Run(); err != nil {
        fmt.Printf("Error making new build directory: %s\n", err)
    }
    
}

huangapple
  • 本文由 发表于 2014年1月13日 20:47:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/21091707.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定