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.1k Fix Google Analytics Redundant Hostnames problem
+31.6k Golang : Regular Expression for alphanumeric and underscore
+16.1k Golang : Find file size(disk usage) with filepath.Walk
+4.1k Golang : Get a list of crosses(instruments) available to trade from Oanda account
+7.9k Golang : Gaussian blur on image and camera video feed examples
+20.1k Golang : Sort and reverse sort a slice of strings
+18.7k Golang : How to count the number of repeated characters in a string?
+5.8k Golang : Calculate diameter, circumference, area, sphere surface and volume
+11.7k Golang : zlib compress file example
+30.3k Golang : Example for ECDSA(Elliptic Curve Digital Signature Algorithm) package functions
+12.5k Golang : reCAPTCHA example
+13.1k Elastic Search : Mapping date format and sort by date