-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdirectories.go
75 lines (60 loc) · 1.25 KB
/
directories.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package main
import (
"fmt"
"io/fs"
"os"
"path/filepath"
)
func check(e error) {
if e != nil {
panic(e)
}
}
func listDir(c []fs.DirEntry) {
for _, entry := range c {
prefix := ""
if entry.IsDir() {
prefix = "d"
} else {
prefix = "-"
}
fmt.Println(prefix, entry.Name())
}
}
func main() {
dir := "/tmp/subdir"
err := os.Mkdir(dir, 0755)
check(err)
defer os.RemoveAll("/tmp/subdir")
createEmptyFile := func(name string) {
d := []byte("")
check(os.WriteFile(name, d, 0644))
}
createEmptyFile("/tmp/subdir/file1")
err = os.MkdirAll("/tmp/subdir/parent/child", 0755)
check(err)
createEmptyFile("/tmp/subdir/parent/file2")
createEmptyFile("/tmp/subdir/parent/file3")
createEmptyFile("/tmp/subdir/parent/child/file4")
c, err := os.ReadDir("/tmp/subdir/parent")
check(err)
listDir(c)
fmt.Println("Listing subdir/parent")
err = os.Chdir("/tmp/subdir/parent/child")
pwd, err:= os.Getwd()
check(err)
fmt.Println("Current directory:", pwd)
c, err = os.ReadDir(".")
listDir(c)
err = os.Chdir("../../..")
check(err)
fmt.Println("Visiting subdir")
err = filepath.Walk("subdir", visit)
}
func visit(p string, info os.FileInfo, err error) error{
if err != nil {
return err
}
fmt.Println(" ", p, info.IsDir())
return nil
}