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
+16.1k Golang : Multi threading or run two processes or more example
+19.7k Curl usage examples with Golang
+10.7k Golang : md5 hash of a string
+8.3k Golang : Terminate-stay-resident or daemonize your program?
+8.3k Golang : Find correlation coefficient example
+12.6k Golang : unknown escape sequence error
+24.5k Golang : How to write CSV data to file
+4.1k Linux/Unix/MacOSX : Find out which application is listening to port 80 or use which IP version
+5.1k Golang : Missing Subversion command
+6.8k Javascript : How to check a browser's Do Not Track status?
+14.5k Golang : Loop each day of the current month example
+18.9k Golang : Count number of digits from given integer value