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
+8.9k Golang : How to profile or log time spend on execution?
+6.3k Golang : Shuffle strings array
+4.1k Unix/Linux : How to archive and compress entire directory ?
+12.6k Golang : convert(cast) string to float value
+4.3k Clean up Visual Studio For Mac installation failed disk full problem
+6.9k How to show different content from website server when AdBlock is detected?
+11.6k Golang : Linear algebra and matrix calculation example
+8.8k Golang : Read file and convert content to string
+4.1k Golang : Detect words using using consecutive letters in a given string
+6.9k Golang : How to check if input string is a word?
+12.4k Golang : Convert IP version 6 address to integer or decimal number
+4.7k Golang : Generate multiplication table from an integer example