How to Detect Data Availability in Go\'s Standard Input (Stdin)?

Susan Sarandon
Release: 2024-11-01 11:17:02
Original
451 people have browsed it

How to Detect Data Availability in Go's Standard Input (Stdin)?

Detecting Data Availability in Standard Input (Stdin) Using Go

In Go, the standard input stream (os.Stdin) can be checked for data using the technique of verifying its file size. Here's how it works:

The os.Stdin can be treated like any regular file, allowing us to examine its properties. To do this, we retrieve a FileInfo object using os.Stdin.Stat(). This object provides various information about the file, including its size.

By checking the file size, we can determine whether the Stdin stream contains data. If its size is greater than zero, it indicates the presence of data. Conversely, a size of zero indicates that Stdin is empty.

Below is a code example that demonstrates this method:

<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

This technique provides an effective way to determine whether os.Stdin has data without blocking the program's execution while waiting for input. It can be particularly useful in cases where you need to dynamically handle incoming data from external sources or processes.

The above is the detailed content of How to Detect Data Availability in Go\'s Standard Input (Stdin)?. 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!