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.3k Responsive Google Adsense
+6.5k Golang : Convert(cast) io.Reader type to string
+27.5k Golang : Saving(serializing) and reading file with GOB
+32.2k Golang : Create x509 certificate, private and public keys
+21.7k Golang : Gorilla mux routing example
+19.9k Golang : GORM create record or insert new record into database example
+8.9k Golang : Find and replace data in all files recursively
+10.6k Golang : Gorilla web tool kit secure cookie example
+38.8k Golang : How do I convert int to uint8?
+2.8k Java : Random alphabets, alpha-numeric or numbers only string generator
+8.9k Golang : Get current, epoch time and display by year, month and day
+4.8k Unix/Linux : How to open tar.gz file ?