Learn how to read and write files using Go.
File handling is essential for saving, retrieving, and processing data efficiently in Go applications.
We use the `os.ReadFile()` function to read the contents of a file.
package main
import (
"fmt"
"os"
)
func main() {
content, err := os.ReadFile("example.txt")
if err != nil {
fmt.Println("Error reading the file:", err)
return
}
fmt.Println(string(content))
}
To write to a file, we use `os.WriteFile()`.
package main
import (
"fmt"
"os"
)
func main() {
text := []byte("Hello, Go!")
err := os.WriteFile("example.txt", text, 0644)
if err != nil {
fmt.Println("Error writing to file:", err)
return
}
fmt.Println("File written successfully!")
}
files.go
.File written successfully!
Hello, Go!
📚 Learn more about file handling in Go:
Official Go Documentation🚀 Enjoying these exercises? If you find them useful and want to support my work, buying me a coffee would be greatly appreciated! ☕😊