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 :

http://golang.org/pkg/os/#File.Write

Advertisement