Directories

Directories

原文:https://gobyexample.com/directories

 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
package main

import (
	"fmt"
	"os"
	"path/filepath"
)

func check(e error) {
	if e != nil {
		panic(e)
	}
}

func main() {

	err := os.Mkdir("subdir", 0755)
	check(err)

	//defer os.RemoveAll("subdir")

	createEmptyFile := func(name string) {
		d := []byte("")
		check(os.WriteFile(name, d, 0644))
	}

	createEmptyFile("subdir/file1")

	err = os.MkdirAll("subdir/parent/child", 0755)
	check(err)

	createEmptyFile("subdir/parent/file2")
	createEmptyFile("subdir/parent/file3")
	createEmptyFile("subdir/parent/child/file4")

	c, err := os.ReadDir("subdir/parent")
	check(err)

	fmt.Println("Listing subdir/parent") // Listing subdir/parent
	for _, entry := range c {
		fmt.Println(" ", entry.Name(), entry.IsDir())
	}
	// child true
	// file2 false
	// file3 false

	err = os.Chdir("subdir/parent/child")
	check(err)

	c, err = os.ReadDir(".")
	check(err)

	fmt.Println("Listing subdir/parent/child") // Listing subdir/parent/child
	for _, entry := range c {
		fmt.Println(" ", entry.Name(), entry.IsDir())
	}
	// file4 false

	err = os.Chdir("../../..")
	check(err)

	fmt.Println("Visiting subdir") // 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())
	//   subdir\parent\file2 false
	//   subdir\parent\file3 false
	return nil
}
最后修改 October 10, 2024: 更新 (a4b8f85)