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
+10.9k Golang : Removes punctuation or defined delimiter from the user's input
+10.7k Golang : Get currencies exchange rates example
+15.8k Golang : How to login and logout with JWT example
+20k Golang : Convert(cast) bytes.Buffer or bytes.NewBuffer type to io.Reader
+9.1k Golang : Get curl -I or head data from URL example
+16k Golang : Read large file with bufio.Scanner cause token too long error
+4.9k Python : Find out the variable type and determine the type with simple test
+10.2k Golang : Text file editor (accept input from screen and save to file)
+5.4k Javascript : How to loop over and parse JSON data?
+19.2k Golang : Execute shell command
+8.8k Golang : HTTP Routing with Goji example
+15.3k Golang : How to get Unix file descriptor for console and file