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
+3.8k Linux : How to set root password in Linux Mint
+6.2k Golang : Gorrila mux.Vars() function example
+19.7k Golang : How to read float value from standard input ?
+17.7k Golang : When to use public and private identifier(variable) and how to make the identifier public or private?
+16.5k Golang : Put UTF8 text on OpenCV video capture image frame
+9.6k Golang : Bubble sort example
+7.1k Golang : Reverse text lines or flip line order example
+10.6k Golang : Convert(cast) bigint to string
+5.9k Golang : Decode XML data from RSS feed
+7.6k Golang : Executing and evaluating nested loop in html template
+5.7k Unix/Linux : How to fix CentOS yum duplicate glibc or device-mapper-libs dependency error?
+4.4k Python : Delay with time.sleep() function example