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
+17.9k Golang : Get all upper case or lower case characters from string example
+8.3k Useful methods to access blocked websites
+32k Golang : Validate email address with regular expression
+6k PHP : Get client IP address
+6.5k Golang : Spell checking with ispell example
+11.9k Golang : Determine if time variables have same calendar day
+6.4k Golang : Handling image beyond OpenCV video capture boundary
+12.8k Python : Convert IPv6 address to decimal and back to IPv6
+4.8k JQuery : Calling a function inside Jquery(document) block
+13.1k Golang : Skip blank/empty lines in CSV file and trim whitespaces example
+15.5k Chrome : ERR_INSECURE_RESPONSE and allow Chrome browser to load insecure content
+28.1k Golang : Connect to database (MySQL/MariaDB) server