Home > Backend Development > Golang > Can Go Access the Initial Standard Input Stream?

Can Go Access the Initial Standard Input Stream?

Susan Sarandon
Release: 2024-12-18 12:21:11
Original
783 people have browsed it

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))
}
Copy after login

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())
    }
}
Copy after login

The above is the detailed content of Can Go Access the Initial Standard Input Stream?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template