snippetgoMajor
How to remove all contents of a directory using Golang?
Viewed 0 times
directoryhowcontentsremoveusinggolangall
Problem
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.
I've tried:
but get
And of course if you do:
it deletes the
I've tried:
os.RemoveAll("/tmp/*")
os.Remove("/tmp/*")but get
remove *: no such file or directory or invalid argument.And of course if you do:
os.RemoveAll("/tmp/")it deletes the
tmp directory as well. Which is not what I want.Solution
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)
}
}Code Snippets
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)
}
}Context
Stack Overflow Q#33450980, score: 51
Revisions (0)
No revisions yet.