Is there a way to check if standard input (os.Stdin) in Go has data without blocking?

Barbara Streisand
Release: 2024-10-31 08:45:29
Original
505 people have browsed it

Is there a way to check if standard input (os.Stdin) in Go has data without blocking?

How to Determine Data Availability in Stdin with Go

Question

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.

Answer

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!