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
+11.6k CodeIgniter : Import Linkedin data
+5.8k Golang : Error handling methods
+14k Golang : Get current time
+8.8k Golang : Heap sort example
+6.7k Golang : How to validate ISBN?
+7.9k Swift : Convert (cast) String to Double
+10.6k Golang : Generate 403 Forbidden to protect a page or prevent indexing by search engine
+18.3k Golang : Put UTF8 text on OpenCV video capture image frame
+17.9k Golang : Iterate linked list example
+12k Golang : Determine if time variables have same calendar day
+7.5k Golang : Gorrila set route name and get the current route name
+5.3k Golang : Print instead of building pyramids