Exercise 5: File Handling in Go

Learn how to read and write files using Go.

Why Work with Files in Go?

File handling is essential for saving, retrieving, and processing data efficiently in Go applications.

Reading a File in Go

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))
}

Writing to a File in Go

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!")
}

Exercise Instructions

Expected Output

File written successfully!
Hello, Go!

Best Practices for File Handling in Go

📚 Learn more about file handling in Go:

Official Go Documentation
← Previous Exercise Next Exercise →

🚀 Enjoying these exercises? If you find them useful and want to support my work, buying me a coffee would be greatly appreciated! ☕😊


☕ Buy me a coffee