Need explanation on error reported from bufio package of golang

Issue

package main

import (
  "bufio"
  "fmt"
  "os"
)

func main() {
  writeBuf := make([]byte, 1)

  fp, err := os.OpenFile("test.d", os.O_CREATE, 0777)
  bf := bufio.NewWriterSize(fp, 3)

  writeBuf = []byte("1")
  writeCount, err := bf.Write(writeBuf)
  fmt.Println(writeCount)

  writeBuf = []byte{'2'}
  writeCount, err = bf.Write(writeBuf)
  fmt.Println(writeCount)

  writeBuf = []byte{'3'}
  writeCount, err = bf.Write(writeBuf)
  fmt.Println(writeCount)

  writeBuf = []byte{'4'}
  writeCount, err = bf.Write(writeBuf)
  if err != nil {
    fmt.Println("Error4:", err)
    os.Exit(-1)
  }
  fmt.Println(writeCount)

  bf.Flush()
  fp.Close()

}

Why does this give the error:

 1
 1
 1
 Error4: write test.d: bad file descriptor
 exit status 255

I thought that NewWriterSize of 3 means that after three bytes are written, the output is flushed. I am getting the error on the 4th write. If I change the NewWriterSize buffer size to 4, it works. For brevity, I have omitted error checks where error is not reported.

Solution

You don’t check the error returned from os.OpenFile. I expect it’s erroring because you need to use O_RDWR or O_WRONLY in the flags (if you want to be able to write to the file). But using os.Create rather than os.OpenFile is easier unless you really need the perm option of os.OpenFile.

Answered By – Paul Hankin

Answer Checked By – Willingham (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.