In Go, is there a reliable way to check if the input stream (os.Stdin) contains data?
The conventional approach of reading from the stream blocks when no data is available, making it impractical for certain use cases.
Similar to other files, os.Stdin can be inspected to determine its size, offering a convenient method for data availability detection.
<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>
By utilizing this technique, you can distinguish between empty and non-empty stdin inputs, allowing for a more flexible handling of data availability.
The above is the detailed content of Is there a way to check if standard input (os.Stdin) in Go has data without blocking?. For more information, please follow other related articles on the PHP Chinese website!