Golang os.File.Write(), WriteString() and WriteAt() functions example
package os
Golang os.File.Write(), WriteString() and WriteAt() functions usage example
package main
import (
"fmt"
"os"
)
func main() {
file, err := os.Create("file.txt")
if err != nil {
panic(err)
}
defer file.Close()
fmt.Println("Writing data to file : ", file.Name())
//----------------------------------------
n, err := file.Write([]byte("Data written to file via os package!"))
if err != nil {
panic(err)
}
file.Sync() // flush to disk
fmt.Printf("%d bytes written with Write() function.\n", n)
//----------------------------------------
n, err = file.WriteString("Data written to file without []byte")
if err != nil {
panic(err)
}
file.Sync() // flush to disk
fmt.Printf("%d bytes written with WriteString() function.\n", n)
//----------------------------------------
// so far we have written 71 bytes into the file. Let's try out WriteAt()
// and start writing from the last written position
n, err = file.WriteAt([]byte("Some binary data perhaps"), 71)
if err != nil {
panic(err)
}
file.Sync() // flush to disk
fmt.Printf("%d bytes written with WriteAt() function.\n", n)
}
NOTE : Similar to some IO package write functions.
See also : https://www.socketloop.com/tutorials/golang-write-file-io-writestring
References :
Advertisement
Something interesting
Tutorials
+8.7k Golang : Load ASN1 encoded DSA public key PEM file example
+8.3k Golang : Temperatures conversion example
+10.2k Golang : Find age or leap age from date of birth example
+8.2k Golang : Create unique title slugs example
+6.2k Golang : Validate credit card example
+6.5k Javascript : Push notifications to browser with Push.js
+5.3k Golang : How to solve "too many .rsrc sections" error?
+35.1k Golang : Convert date or time stamp from string to time.Time type
+10.5k How to tell if a binary(executable) file or web application is built with Golang?
+5.8k Golang : Get expvar(export variables) to work with multiplexer
+6.4k Android Studio : AlertDialog to get user attention example
+5.9k Golang : Pat multiplexer routing example