How can I close bufio.Reader
or bufio.Writer
in golang?
func init(){
file,_ := os.Create("result.txt")
writer = bufio.NewWriter(file)
}
Should I close Writer
? or just use file.Close()
will make Writer
close?
In Golang, bufio is a package used for buffered IO. Buffering IO is a technique used to temporarily accumulate the results for an IO operation before transmitting it forward. This technique can increase the speed of a program by reducing the number of system calls, which are typically slow operations.
Overview. Package bufio implements buffered I/O. It wraps an io. Reader or io. Writer object, creating another object (Reader or Writer) that also implements the interface but provides buffering and some help for textual I/O.
As far as I know, you can't close the bufio.Writer
.
What you do is to Flush()
the bufio.Writer
and then Close()
the os.Writer
:
writer.Flush()
file.Close()
I think the following is canonical:
func doSomething(filename string){
file, err := os.Create(filename)
// check err
defer file.Close()
writer = bufio.NewWriter(file)
defer writer.Flush()
// use writer here
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With