Golang : Flush and close file created by os.Create and bufio.NewWriter example
Whenever a new file is created by os.Create()
function and data being written to the file with bufio.NewWriter()
. It is a good practise to flush all the data from memory to the file before closing the file. This is to ensure that the write is complete and no corruption at the file level.
For instance :
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
file, _ := os.Create("result.txt")
defer file.Close() // don't forget to defer close!
fileWriter := bufio.NewWriter(file)
fmt.Fprint(fileWriter, "Hello, ")
fmt.Fprint(fileWriter, "world! 你好世界!\n")
fileWriter.Flush() // Don't forget to flush!
}
Reference :
https://www.socketloop.com/references/golang-bufio-newwriter-function-example
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
+6.9k Golang : Word limiter example
+33k Golang : All update packages with go get command
+6k Golang : Convert an executable file into []byte example
+14.9k Golang : rune literal not terminated error
+9.1k Golang : ffmpeg with os/exec.Command() returns non-zero status
+10.6k Golang : Proper way to test CIDR membership of an IP 4 or 6 address example
+11.2k How to tell if a binary(executable) file or web application is built with Golang?
+10.1k Swift : Convert (cast) String to Integer
+7.7k Golang : Get final or effective URL with Request.URL example
+8.5k Golang : Get SPF and DMARC from email headers to fight spam
+14.3k Golang : Save(pipe) HTTP response into a file
+25.5k Mac/Linux and Golang : Fix bind: address already in use error