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
+4.7k JQuery : Calling a function inside Jquery(document) block
+11.4k Get form post value in Go
+18.1k Golang : Get path name to current directory or folder
+6.7k Golang : Pat multiplexer routing example
+4.5k Chrome : How to block socketloop.com links in Google SERP?
+10.9k Golang : Roll the dice example
+16.6k Golang : Set up source IP address before making HTTP request
+14.7k Golang : Search folders for file recursively with wildcard support
+13.2k Golang : Count number of runes in string
+30.6k error: trying to remove "yum", which is protected
+19k Golang : Get RGBA values of each image pixel
+11.6k Golang : Setup API server or gateway with Caddy and http.ListenAndServe() function example