Determine if Stdin has data with Go

后端 未结 2 964
北海茫月
北海茫月 2021-01-12 07:38

Is there a way to check if the input stream (os.Stdin) has data?

The post Read from initial stdin in GO? shows how to read the data, but unfortunately b

2条回答
  •  不知归路
    2021-01-12 08:37

    os.Stdin is like any other "file", so you can check it's size:

    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")
        }
    }
    

    I built this as a "pipe" executable, here is how it works:

    $ ./pipe
    Stdin is empty
    $ echo test | ./pipe
    5 bytes available in Stdin
    

提交回复
热议问题