Golang : Append content to a file
In this tutorial, we will learn how to open a file with specific mode such as for appending data when writing. This means that the operation depends on how the file is opened initially.
Example of appending content to a file :
appendfile.go
package main
import (
"os"
"fmt"
)
func main () {
// open files r and w
file, err := os.OpenFile("input.txt", os.O_APPEND|os.O_WRONLY,0600)
if err != nil {
panic(err)
}
defer file.Close()
if _, err = file.WriteString(" this is the APPENDED text"); err != nil {
panic(err)
}
fmt.Printf("Appended into file\n")
}
There is a reference at the page bottom on what os.O_APPEND
and os.O_WRONLY
parameters about.
Reference :
Extract from http://golang.org/src/pkg/os/file.go
// Flags to Open wrapping those of the underlying system. Not all flags
// may be implemented on a given system.
const (
O_RDONLY int = syscall.O_RDONLY // open the file read-only.
O_WRONLY int = syscall.O_WRONLY // open the file write-only.
O_RDWR int = syscall.O_RDWR // open the file read-write.
O_APPEND int = syscall.O_APPEND // append data to the file when writing.
O_CREATE int = syscall.O_CREAT // create a new file if none exists.
O_EXCL int = syscall.O_EXCL // used with O_CREATE, file must not exist
O_SYNC int = syscall.O_SYNC // open for synchronous I/O.
O_TRUNC int = syscall.O_TRUNC // if possible, truncate file when opened.
)
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+4.5k Unix/Linux : How to pipe/save output of a command to file?
+11.1k Golang : Characters limiter example
+35.8k Golang : How to split or chunking a file to smaller pieces?
+9.3k Golang : How to generate Code 39 barcode?
+7.2k Golang : Hue, Saturation and Value(HSV) with OpenCV example
+24.9k Golang : Storing cookies in http.CookieJar example
+5.8k Linux/MacOSX : Search for files by filename and extension with find command
+14.9k Golang : How to get Unix file descriptor for console and file
+4.4k Adding Skype actions such as call and chat into web page examples
+7.9k Golang : Add build version and other information in executables
+22.2k Golang : Convert Unix timestamp to UTC timestamp
+23.2k Golang : minus time with Time.Add() or Time.AddDate() functions to calculate past date