append to a file in go

To append data to an existing file in Go, we first need to open the file in append mode. We can do that using the os.OpenFile() function with the appropriate flags. Once we have the file descriptor, we can use the io.WriteString() function to write the new data to the end of the file. Here's an example:

main.go
package main

import (
    "io"
    "os"
)

func main() {
    // open file in append mode, create if not exist
    f, err := os.OpenFile("data.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
    if err != nil {
        panic(err)
    }
    defer f.Close()

    // write new data to file
    data := []byte("new data\n")
    if _, err := io.WriteString(f, string(data)); err != nil {
        panic(err)
    }
}
411 chars
22 lines

In the code sample above, we open the file "data.txt" in append mode, creating it if it doesn't exist. We then write the new data "new data\n" to the end of the file using the io.WriteString() function. Finally, we close the file descriptor using defer to ensure it gets closed when the function exits.

related categories

gistlibby LogSnag