Introduction
Working with directories is a common task in many Go programs. The os package provides various functions to create, read, and manage directories. In this chapter, you will learn the basics of working with directories in Go, including how to create, read, traverse, and delete directories, as well as handling directory permissions.
Creating Directories
Creating a Single Directory
The os.Mkdir function creates a single directory with specified permissions.
Example:
package main
import (
"log"
"os"
)
func main() {
err := os.Mkdir("exampledir", 0755)
if err != nil {
log.Fatal(err)
}
}
In this example, os.Mkdir creates a directory named exampledir with permissions 0755.
Creating Nested Directories
The os.MkdirAll function creates a directory along with any necessary parents.
Example:
package main
import (
"log"
"os"
)
func main() {
err := os.MkdirAll("parent/child/grandchild", 0755)
if err != nil {
log.Fatal(err)
}
}
In this example, os.MkdirAll creates the entire directory path parent/child/grandchild.
Reading Directories
Reading Directory Contents
The os.ReadDir function reads the contents of a directory and returns a slice of os.DirEntry.
Example:
package main
import (
"fmt"
"log"
"os"
)
func main() {
entries, err := os.ReadDir(".")
if err != nil {
log.Fatal(err)
}
for _, entry := range entries {
fmt.Println(entry.Name())
}
}
In this example, os.ReadDir reads the contents of the current directory (.) and prints the name of each entry.
Reading Directory Contents with os.File
Alternatively, you can use os.Open and Readdir to read directory contents.
Example:
package main
import (
"fmt"
"log"
"os"
)
func main() {
dir, err := os.Open(".")
if err != nil {
log.Fatal(err)
}
defer dir.Close()
entries, err := dir.Readdir(-1)
if err != nil {
log.Fatal(err)
}
for _, entry := range entries {
fmt.Println(entry.Name())
}
}
In this example, os.Open opens the directory, and Readdir reads its contents.
Traversing Directories
Walking a Directory Tree
The filepath.Walk function is used to traverse a directory tree, calling a specified function for each file or directory.
Example:
package main
import (
"fmt"
"log"
"path/filepath"
)
func main() {
root := "."
err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
fmt.Println(path)
return nil
})
if err != nil {
log.Fatal(err)
}
}
In this example, filepath.Walk traverses the directory tree starting from the current directory (.) and prints each path.
Deleting Directories
Removing a Single Directory
The os.Remove function removes a single directory, provided it is empty.
Example:
package main
import (
"log"
"os"
)
func main() {
err := os.Remove("exampledir")
if err != nil {
log.Fatal(err)
}
}
In this example, os.Remove removes the exampledir directory if it is empty.
Removing a Directory and Its Contents
The os.RemoveAll function removes a directory along with any contents it contains.
Example:
package main
import (
"log"
"os"
)
func main() {
err := os.RemoveAll("parent")
if err != nil {
log.Fatal(err)
}
}
In this example, os.RemoveAll removes the parent directory and all its contents.
Handling Directory Permissions
Permissions are specified using Unix-style permission bits. The most common permissions are 0755 (owner can read/write/execute, others can read/execute) and 0644 (owner can read/write, others can read).
Example: Creating a Directory with Specific Permissions
Example:
package main
import (
"log"
"os"
)
func main() {
err := os.Mkdir("secure", 0700)
if err != nil {
log.Fatal(err)
}
}
In this example, os.Mkdir creates a secure directory with permissions 0700 (only the owner can read/write/execute).
Changing Directory Permissions
The os.Chmod function changes the permissions of an existing directory.
Example: Changing Directory Permissions
Example:
package main
import (
"log"
"os"
)
func main() {
err := os.Chmod("exampledir", 0755)
if err != nil {
log.Fatal(err)
}
}
In this example, os.Chmod changes the permissions of exampledir to 0755.
Conclusion
Handling directories in Go is straightforward with the os and path/filepath packages. You can create, read, traverse, and delete directories, as well as manage directory permissions. By understanding these basic operations, you can effectively manage directories in your Go programs, ensuring that your file system interactions are robust and reliable.