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
+7.1k Golang : Variadic function arguments sanity check example
+12.8k Golang : Chunk split or divide a string into smaller chunk example
+23.4k Golang : Change file read or write permission example
+4.7k Golang : Configure crontab to poll every two minutes 8am to 6pm Monday to Friday
+5.5k Golang : Embedded or data bundling example
+11.5k Golang : How to calculate the distance between two coordinates using Haversine formula
+13.5k Golang : Find commonalities in two slices or arrays example
+12.5k Golang : Tutorial on loading GOB and PEM files
+40.6k Golang : Convert []byte to image
+8k Golang : Inject/embed Javascript before sending out to browser example
+4.5k Swift : Convert string array to array example
+4.4k PHP : Fix Call to undefined function curl_init() error