67 lines
1.4 KiB
Go
67 lines
1.4 KiB
Go
package dir
|
|
|
|
import (
|
|
"fmt"
|
|
"io/fs"
|
|
"os"
|
|
"path/filepath"
|
|
)
|
|
|
|
func check(err error) {
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
}
|
|
|
|
func createEmptyFile(p string) {
|
|
check(os.WriteFile(p, []byte(""), 0700))
|
|
}
|
|
|
|
func Dir() {
|
|
dirPath := "/tmp/gobyex-tempdir"
|
|
err := os.Mkdir(dirPath, 0700)
|
|
check(err)
|
|
defer os.RemoveAll(dirPath)
|
|
|
|
createEmptyFile(filepath.Join(dirPath, "file1"))
|
|
|
|
check(os.MkdirAll(filepath.Join(dirPath, "child", "grandchild"), 0700))
|
|
|
|
createEmptyFile(filepath.Join(dirPath, "child", "grandchild", "file1"))
|
|
createEmptyFile(filepath.Join(dirPath, "child", "grandchild", "file2"))
|
|
createEmptyFile(filepath.Join(dirPath, "child", "grandchild", "file3"))
|
|
|
|
check(os.Mkdir(filepath.Join(dirPath, "child", "grandchild", "dir1"), 0700))
|
|
|
|
entries, err := os.ReadDir(filepath.Join(dirPath, "child", "grandchild"))
|
|
check(err)
|
|
|
|
fmt.Println("Lisitng", filepath.Join(dirPath, "child", "grandchild"))
|
|
for _, entry := range entries {
|
|
fmt.Printf("%s, is dir? %t\n", entry.Name(), entry.IsDir())
|
|
}
|
|
|
|
check(os.Chdir(dirPath))
|
|
|
|
entries, err = os.ReadDir(".")
|
|
check(err)
|
|
|
|
fmt.Println("Listing", dirPath)
|
|
for _, entry := range entries {
|
|
fmt.Printf("%s, is dir? %t\n", entry.Name(), entry.IsDir())
|
|
}
|
|
|
|
fmt.Println("Walking the file tree at", dirPath)
|
|
// WalkDir is more efficient than Walk
|
|
check(filepath.WalkDir(".", walk))
|
|
}
|
|
|
|
func walk(p string, d fs.DirEntry, err error) error {
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
fmt.Println(" ", p, "is dir?", d.IsDir())
|
|
return nil
|
|
}
|