需要解释一下关于 Golang 的 bufio 包报告的错误。

huangapple go评论76阅读模式
英文:

Need explanation on error reported from bufio package of golang

问题

以下是代码的翻译:

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()

}

为什么会出现错误:

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

我以为 NewWriterSize 的参数为 3 意味着在写入三个字节后会刷新输出。但是我在第四次写入时出现了错误。如果我将 NewWriterSize 的缓冲区大小更改为 4,它就可以正常工作。为了简洁起见,我省略了一些没有报告错误的错误检查部分。

英文:
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.

答案1

得分: 1

你没有检查从os.OpenFile返回的错误。我猜想这是因为你需要在flags中使用O_RDWR或O_WRONLY(如果你想要能够写入文件)。但是,除非你真的需要os.OpenFile的perm选项,否则使用os.Create比使用os.OpenFile更简单。

英文:

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.

huangapple
  • 本文由 发表于 2022年1月30日 01:30:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/70908019.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定