gpt4 book ai didi

go - 从 golang 中的标准输入读取

转载 作者:IT王子 更新时间:2023-10-29 01:22:07 32 4
gpt4 key购买 nike

我正在尝试从 Golang 中的 Stdin 读取,因为我正在尝试为 Erlang 实现驱动程序。我有以下代码:

package main

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

func main() {
go func() {
stdout := bufio.NewWriter(os.Stdin)
p := []byte{121,100,125,'\n'}
stdout.Write(p)
}()
stdin := bufio.NewReader(os.Stdin)
values := make([]byte,4,4)
for{
fmt.Println("b")
if read_exact(stdin) > 0 {
stdin.Read(values)
fmt.Println("a")
give_func_write(values)
}else{
continue
}
}
}




func read_exact(r *bufio.Reader) int {
bits := make([]byte,3,3)
a,_ := r.Read(bits)
if a > 0 {
r.Reset(r)
return 1
}
return -1
}

func give_func_write(a []byte) bool {
fmt.Println("Yahu")
return true
}

然而,似乎从未达到 give_func_write。我试图在 2 秒后启动一个 goroutine 来写入标准输入以测试这一点。

我在这里错过了什么?还有 r.Reset(r) 行。这有效吗?我试图实现的只是从文件开头重新开始读取。有没有更好的办法?

编辑

玩过之后我发现代码卡在 read_exact 函数的 a,_ := r.Read(bits)

最佳答案

I guess that I will need to have a protocol in which I send a \n to make the input work and at the same time discard it when reading it

不,你不知道。标准输入只有在绑定(bind)到终端时才是行缓冲的。您可以运行您的程序 prog < /dev/zerocat file | prog

bufio.NewWriter(os.Stdin).Write(p)

您可能不想写信给 stdin 。详情参见“Writing to stdin and reading from stdout”。

好吧,我不太清楚您要实现的目标。我假设您只想按固定大小的 block 从 stdin 读取数据。为此使用 io.ReadFull。或者如果你想使用缓冲区,你可以使用 Reader.PeekScanner 来确保特定数量的字节可用。我已经更改了您的程序以演示 io.ReadFull 的用法:

package main

import (
"fmt"
"io"
"time"
)

func main() {
input, output := io.Pipe()

go func() {
defer output.Close()
for _, m := range []byte("123456") {
output.Write([]byte{m})
time.Sleep(time.Second)
}
}()

message := make([]byte, 3)
_, err := io.ReadFull(input, message)
for err == nil {
fmt.Println(string(message))
_, err = io.ReadFull(input, message)
}
if err != io.EOF {
panic(err)
}
}

您可以轻松地将它分成两个程序并以这种方式进行测试。只需将 input 更改为 os.Stdin 即可。

关于go - 从 golang 中的标准输入读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29060922/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com