Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I close bufio.Reader/Writer in golang?

Tags:

go

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?

like image 378
WoooHaaaa Avatar asked Nov 22 '12 12:11

WoooHaaaa


People also ask

What does Bufio do in Golang?

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.

What is bufio Reader?

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.


2 Answers

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()
like image 147
ANisus Avatar answered Sep 21 '22 15:09

ANisus


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
}
like image 22
Dima Tisnek Avatar answered Sep 22 '22 15:09

Dima Tisnek