如何从 Golang 的 stdin 读取大量数据?目前我的所有读取都停止在 4095 字节。我已经尝试了很多东西,但我当前的代码如下所示:
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
}
我也尝试过使用扫描仪,但不知道如何退出
for scanner.Scan() {
data = append(data, scanner.Bytes()...)
}
当发生换行时(即当用户按下回车键时)。
我也尝试过 ReadBytes('\n') 但即使这样也停在 4095 字节。除了增加缓冲区的大小(这只是一个丑陋的黑客)之外,我不知道此时该怎么做。
如果您查看 Go 源代码,您会发现它使用默认缓冲区大小:
func NewReader(rd io.Reader) *Reader {
return NewReaderSize(rd, defaultBufSize)
}
所以你可以在你的代码中使用:
var stdinReader = bufio.NewReaderSize(os.Stdin, 10000)
附:
Go 是开源的,因此您只需查看内部结构就可以学到很多东西。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)