Read from stdin and write to stdout in Go using os.Stdin, os.Stdout, and bufio.Scanner for efficient line processing.
Use os.Stdin as the reader and os.Stdout as the writer, typically wrapped in bufio for efficient line-by-line processing.
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
fmt.Fprintln(os.Stdout, scanner.Text())
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
}
}
Reading from stdin and writing to stdout lets your program accept text typed by a user or piped from another command and immediately display the result on the screen. It works like a relay station that takes input from one pipe and sends it directly to another without saving it to a file. You use this when building command-line tools that need to process data streams in real-time.