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
+15.6k Golang : How to login and logout with JWT example
+13k Golang : Handle or parse date string with Z suffix(RFC3339) example
+8k Golang : Append and add item in slice
+8.1k Golang : Reverse text lines or flip line order example
+23.4k Golang : minus time with Time.Add() or Time.AddDate() functions to calculate past date
+27.3k Golang : Convert integer to binary, octal, hexadecimal and back to integer
+8.5k Python : Fix SyntaxError: Non-ASCII character in file, but no encoding declared
+8.3k Golang : How to check if input string is a word?
+12.5k Golang : Sort and reverse sort a slice of bytes
+11.1k Golang : Intercept and process UNIX signals example
+5.2k Golang : Get FX sentiment from website example
+11.4k Swift : Convert (cast) Float to String