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:
- Import necessary packages:
fmt
for formatting andos
for file operations. - Define the filename (
example.txt
) and the content to be appended to the file. - 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
). - Check if any error occurs while opening the file. If there is an error, print an error message and return.
- Defer the closing of the file to ensure it's closed properly at the end of the function.
- Use
file.WriteString
to append the specified content to the file. - Check if any error occurs while writing to the file. If there is an error, print an error message and return.
- If successful, print a message indicating that the content was appended to the file successfully.