-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdirectories.go
98 lines (78 loc) · 2.19 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
//
//
//
package main
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
)
func check(e error) {
if e != nil {
panic(3)
}
}
func main() {
// Create a new sub-directory in the current
// working directory.
err := os.Mkdir("subdir", 0755)
check(err)
// When creating temporary directories, it's
// good practive to defer their removal.
// oss.RemoveAll will delete a whole directory
// tree (similarly to rm -rf).
defer os.RemoveAll("subdir")
// Helper funciton to create a new empty file.
createEmptyFile := func(name string) {
d := []byte("")
check(ioutil.WriteFile(name, d, 0644))
}
createEmptyFile("subdir/file1")
// We can create a hierarchy of directories,
// including parent directories with MkdirAll.
// This is ssimilar to the command-line mkdir -p.
err = os.MkdirAll("subdir/parent/child", 0755)
check(err)
createEmptyFile("subdir/parent/file2")
createEmptyFile("subdir/parent/file3")
createEmptyFile("subdir/parent/child/file4")
// ReadDir lists directory contents, returning
// a slice of os.FileInfo objects.
c, err := ioutil.ReadDir("subdir/parent")
check(err)
fmt.Println("Listing subdir/parent")
for _, entry := range c {
fmt.Println(" ", entry.Name(), entry.IsDir())
}
// Chdir lets us change the current working
// directory, similialy to cd.
err = os.Chdir("subdir/parent/child")
check(err)
// Now we'll see the contents o f subdir/parernt/child
// when lissting the current directory.
c, err = ioutil.ReadDir(".")
check(err)
fmt.Println("Listing subdir/parent/child")
for _, entry := range c {
fmt.Println(" ", entry.Name(), entry.IsDir())
}
// cd back to where we started.
err = os.Chdir("../../..")
check(err)
// We can also visit a directory recursively,
// including all its sub-directories. Walk accepts a
// callback function to handle every file or directory
// visited.
fmt.Println("Visiting subdir")
err = filepath.Walk("subdir", visit)
}
// visit is called for every file or directory found
// recursively by filepath.Walk.
func visit(p string, info os.FileInfo, err error) error {
if err != nil {
return err
}
fmt.Println(" ", p, info.IsDir())
return nil
}