append to file in golang

package main

import (
    "fmt"
    "os"
)

func main() {
    fileName := "example.txt"
    content := "This is some text to append."

    file, err := os.OpenFile(fileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
    if err != nil {
        fmt.Println("Error opening file:", err)
        return
    }
    defer file.Close()

    _, err = file.WriteString(content)
    if err != nil {
        fmt.Println("Error writing to file:", err)
        return
    }

    fmt.Println("Content appended to file successfully.")
}

This Go code demonstrates how to append content to a file. Here are the steps:

  1. Import necessary packages: fmt for formatting and os for file operations.
  2. Define the filename (example.txt) and the content to be appended to the file.
  3. Use os.OpenFile to open the file in append mode (os.O_APPEND), create the file if it doesn't exist (os.O_CREATE), and set the file to be writable only (os.O_WRONLY). It also specifies file permissions (in this case, 0644).
  4. Check if any error occurs while opening the file. If there is an error, print an error message and return.
  5. Defer the closing of the file to ensure it's closed properly at the end of the function.
  6. Use file.WriteString to append the specified content to the file.
  7. Check if any error occurs while writing to the file. If there is an error, print an error message and return.
  8. If successful, print a message indicating that the content was appended to the file successfully.