How to Check if Stdin Has Data in Go?

Mary-Kate Olsen
Release: 2024-11-02 04:08:02
Original
793 people have browsed it

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

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

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!

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!