如何使用Golang删除目录的所有内容? [英] How to remove all contents of a directory using Golang?

查看:62
本文介绍了如何使用Golang删除目录的所有内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Go的新手,似乎不知道删除目录中所有内容的方法.

I'm new to Go and can't seem to find a way to delete all the contents of a directory when I don't know the contents.

我尝试过:

os.RemoveAll("/tmp/*")
os.Remove("/tmp/*")

但是得到 remove *:没有这样的文件或目录无效的参数.

当然,如果您这样做:

os.RemoveAll("/tmp/")

它也会删除 tmp 目录.这不是我想要的.

it deletes the tmp directory as well. Which is not what I want.

推荐答案

编写一个简单的 RemoveContents 函数.例如,

Write a simple RemoveContents function. For example,

package main

import (
    "fmt"
    "os"
    "path/filepath"
    "strings"
)

func RemoveContents(dir string) error {
    d, err := os.Open(dir)
    if err != nil {
        return err
    }
    defer d.Close()
    names, err := d.Readdirnames(-1)
    if err != nil {
        return err
    }
    for _, name := range names {
        err = os.RemoveAll(filepath.Join(dir, name))
        if err != nil {
            return err
        }
    }
    return nil
}

func main() {
    dir := strings.TrimSuffix(filepath.Base(os.Args[0]), filepath.Ext(os.Args[0]))
    dir = filepath.Join(os.TempDir(), dir)
    dirs := filepath.Join(dir, `tmpdir`)
    err := os.MkdirAll(dirs, 0777)
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    file := filepath.Join(dir, `tmpfile`)
    f, err := os.Create(file)
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    f.Close()
    file = filepath.Join(dirs, `tmpfile`)
    f, err = os.Create(file)
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    f.Close()

    err = RemoveContents(dir)
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
}

这篇关于如何使用Golang删除目录的所有内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆