Reputation: 21
I would like to be able to read fully from stdin and then get input, also from stdin. I can read the input sent to my code but then I can't read user input. Is there any way around this? I'm doing this as part of a paging tool I am writing.
Read incoming
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
sb.WriteString(fmt.Sprintf("%s\n", scanner.Text()))
}
Reading user input
reader := bufio.NewReader(os.Stdin)
text, _ := reader.ReadString('\n')
Here is part of the code that reads from stdin then tries to read from input. When stdin is read first ReadString('\n') does not wait and results in a zero length string. If ReadString is read but the initial read from stdin is not made ReadString waits properly. I get EOF in the second call. I'll look into this and see what I can do.
var r = bufio.NewReader(os.Stdin)
var contents string
var err error
contents, err = io.ReadAll(r)
if err != nil {
panic(err)
}
text, err := r.ReadString('\n')
if err != nil {
fmt.Println(err)
}
fmt.Println(txt)
Upvotes: 1
Views: 1183
Reputation: 165456
My code first reads any input from stdin. I use cat to send text to the program. When I do that I can read the input from stdin but if I then try to read typed in input using reader.ReadString('\n') or fmt.Scanln() nothing is picked up.
You're running your program like cat file.txt | program
and then you're typing more input and trying to read that, too.
A program's stdin is normally inherited from the parent process. If you're running from an interactive shell, that's input from the terminal (ie. the keyboard).
cat file.txt | program
redirects stdin to read from the output of cat
. Stdin no longer points at the input from the terminal.
You'll have to reopen a stream to the terminal and write to that. You do this by reading from /dev/tty
. tty, err := os.Open("/dev/tty")
.
Upvotes: 2