"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Can Go Access the Initial Standard Input Stream?

Can Go Access the Initial Standard Input Stream?

Published on 2024-12-23
Browse:115

Can Go Access the Initial Standard Input Stream?

In Go, Can You Access Initial Standard Input?

In Go, using os.Stdin to read from the original standard input should yield the desired results, as demonstrated by this code snippet:

package main

import "os"
import "log"
import "io"

func main() {
    bytes, err := io.ReadAll(os.Stdin)

    log.Println(err, string(bytes))
}

When you execute echo test stdin | go run stdin.go, the program should print test stdin without issues.

If you encounter errors, providing the code you used will greatly help in identifying the problem.

For handling line-based input, you can utilize bufio.Scanner:

import "os"
import "log"
import "bufio"

func main() {
    s := bufio.NewScanner(os.Stdin)
    for s.Scan() {
        log.Println("line", s.Text())
    }
}
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3