This commit is contained in:
Eli Bendersky
2019-06-08 11:20:00 -07:00
parent ee8c401ac3
commit 1be2c1c910
4 changed files with 89 additions and 17 deletions

View File

@@ -7,6 +7,7 @@ import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
)
func check(e error) {
@@ -53,7 +54,7 @@ func main() {
fmt.Println("Listing subdir/parent")
for _, entry := range c {
fmt.Println(entry.Name(), entry.IsDir())
fmt.Println(" ", entry.Name(), entry.IsDir())
}
// `Chdir` lets us change the current working directory,
@@ -68,10 +69,27 @@ func main() {
fmt.Println("Listing subdir/parent/child")
for _, entry := range c {
fmt.Println(entry.Name(), entry.IsDir())
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
}

View File

@@ -1,2 +1,2 @@
7b2eed223a00c8a84df582bd254a642c7a57dd9b
UnjBL6NmR8-
57a8f629f040270c15a0375be4424b392edf3c95
LI7ty_KDozd

View File

@@ -1,7 +1,15 @@
$ go run directories.go
Listing subdir/parent
child true
file2 false
file3 false
child true
file2 false
file3 false
Listing subdir/parent/child
file4 false
file4 false
Visiting subdir
subdir true
subdir/file1 false
subdir/parent true
subdir/parent/child true
subdir/parent/child/file4 false
subdir/parent/file2 false
subdir/parent/file3 false