Home >Backend Development >Golang >How to Check if Stdin Has Data in Go?
How to Find Out If Stdin Has Data with Go
When working with input streams in Go, you may encounter situations where you need to determine whether os.Stdin has any data available. This can be useful in various scenarios, such as deciding whether to proceed with reading input or displaying a prompt to the user.
Solution:
os.Stdin can be treated akin to any other file descriptor in Go. To check if it has data, you can examine its size:
<code class="go">package main import ( "fmt" "os" ) func main() { file := os.Stdin fi, err := file.Stat() if err != nil { fmt.Println("file.Stat()", err) } size := fi.Size() if size > 0 { fmt.Printf("%v bytes available in Stdin\n", size) } else { fmt.Println("Stdin is empty") } }</code>
Usage:
You can compile this code into an executable and use it like a pipe:
$ ./pipe Stdin is empty $ echo test | ./pipe 5 bytes available in Stdin
This example demonstrates that when no data is piped into stdin, the program reports an empty stdin, and when data is piped in, it correctly indicates the available bytes.
The above is the detailed content of How to Check if Stdin Has Data in Go?. For more information, please follow other related articles on the PHP Chinese website!