Welcome to our deep dive into the io/fs package in Go! This powerful toolkit helps you work with the file system in a practical and efficient way. Let's explore its fascinating world together.
io/fs Package 📝The io/fs package is a part of Go's standard library and offers a unified interface for interacting with the file system. It simplifies various file system operations and makes writing robust file system tools easier.
To read and write files, we'll make use of two types: ReadCloser and WriterTo.
Here's a simple example of reading a file:
package main
import (
"bufio"
"log"
"os"
"io/fs"
)
func main() {
file, err := os.Open("example.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
reader := bufio.NewReader(file)
for {
line, err := reader.ReadString('\n')
if err != nil {
break
}
fmt.Print(line)
}
}Writing to a file is similarly easy:
package main
import (
"fmt"
"io"
"os"
"io/fs"
)
func main() {
file, err := os.Create("example.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
_, err = file.WriteString("Hello, World!\n")
if err != nil {
log.Fatal(err)
}
}Managing directories in Go is just as straightforward. Here's how you can create, read, and remove directories:
package main
import (
"fmt"
"os"
"io/fs"
)
func main() {
err := os.MkdirAll("mydir", fs.ModePerm)
if err != nil {
log.Fatal(err)
}
files, err := os.ReadDir("mydir")
if err != nil {
log.Fatal(err)
}
fmt.Println("Files in mydir:", files)
err = os.RemoveAll("mydir")
if err != nil {
log.Fatal(err)
}
}What does the `os.ReadDir` function do?
io/fs Functionality 💡As you progress, you'll encounter more advanced topics, such as:
Each of these topics will be covered in future lessons. Stay tuned as we continue our journey through the world of the io/fs package! 🎯
Happy coding! 💻