Skip to content

Instantly share code, notes, and snippets.

@terngkub
Created October 2, 2018 08:27
Show Gist options
  • Select an option

  • Save terngkub/f1fd462d9eaec4bf9cd44a0eeed85f1c to your computer and use it in GitHub Desktop.

Select an option

Save terngkub/f1fd462d9eaec4bf9cd44a0eeed85f1c to your computer and use it in GitHub Desktop.
Golang. Append string to a file. If the file didn't exist, created it.
package main
import (
"log"
"os"
)
func appendFile(fileName, content string) {
file, err := os.OpenFile(fileName, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)
if err != nil {
log.Fatal(err)
}
defer file.Close()
if _, err = file.WriteString(content); err != nil {
log.Fatal(err)
}
}
func main() {
appendFile("test.txt", "Hello")
appendFile("test.txt", " World\n")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment