dongshen4129 2017-03-14 07:17
浏览 148

从标准输入读取大量数据

How do you read lots of data from stdin in Golang? All of my reads currently stop at 4095 bytes. I've tried lots of things but my current code looks like:

var stdinReader = bufio.NewReader(os.stdin)

// Input reads from stdin while echoing back.
func Input(prompt string) []byte {
    var data []byte

    // Output prompt.
    fmt.Print(prompt)

    // Read until newline.
    for {
        bytes, isPrefix, _ := stdinReader.ReadLine()
        data = append(data, bytes...)

        if !isPrefix {
            break
        }
    }

    // Everything went well. Return the data.
    return data
}

I've also tried using a scanner but couldn't figure out how to exit

for scanner.Scan() {
    data = append(data, scanner.Bytes()...)
}

when a newline occurred (i.e. when the user pressed return).

I also tried ReadBytes(' ') but even that stopped at 4095 bytes. Short of increasing the size of the buffer (which is just an ugly hack) I'm not sure what to do at this point.

  • 写回答

2条回答 默认 最新

  • doucanrui1735 2017-03-14 12:26
    关注

    If you'll look at Go sources, you will see that it uses default buffer size:

    func NewReader(rd io.Reader) *Reader {
        return NewReaderSize(rd, defaultBufSize)
    }
    

    So you can use in your code as:

    var stdinReader = bufio.NewReaderSize(os.Stdin, 10000)
    

    P.S. Go is open source, so you can learn a lot just from looking inside internals.

    评论

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程