Bufio中的一些疑问

derek718 · 2017-09-01 03:04:16 · 1029 次点击 · 大约8小时之前 开始浏览    置顶
这是一个创建于 2017-09-01 03:04:16 的主题,其中的信息可能已经有所发展或是发生改变。

各位大神可以帮忙解读下面的代码吗?菜鸟刚写,有的地方了解得不透

万分感激

func main() {
    sr := strings.NewReader("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890")
    buf := bufio.NewReaderSize(sr, 0)
    b := make([]byte, 10)

    //返回缓存区,未读取的数据长度
    fmt.Println(buf.Buffered())

    s, _ := buf.Peek(5)
    s[0], s[1], s[2] = 'a', 'b', 'c'

    fmt.Printf("%d   %q\n", buf.Buffered(), s)
    buf.Discard(1)
    fmt.Println(buf.Buffered())
    for n, err := 0, error(nil); err == nil; {
        n, err = buf.Read(b)
        fmt.Printf("%q", b[:])
        fmt.Printf("%d  %q  %v\n", buf.Buffered(), b[:n], err)
    }
}
  1. fmt.Println(buf.Buffered())这里为什么输出的是 "0"
  2. fmt.Printf("%q", b[:])l输出的会有重复字符
  3. fmt.Printf("%d %q %v\n", buf.Buffered(), b[:n], err) n返回字节数有时候为啥是0、5、6为何不是10呢?

有疑问加站长微信联系(非本文作者)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1029 次点击  
加入收藏 微博
1 回复  |  直到 2017-09-01 04:04:00
marlonche
marlonche · #1 · 8年之前

这些问题在标准库的文档里面都可以找到答案:

type Reader

If some data is available but not len(p) bytes, Read conventionally returns what is available instead of waiting for more.

Callers should always process the n > 0 bytes returned before considering the error err. Doing so correctly handles I/O errors that happen after reading some bytes and also both of the allowed EOF behaviors.

如果想把buf读满再返回,可以用io.ReadFull(), 返回nil表示读满了

func ReadFull(r Reader, buf []byte) (n int, err error)

添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传