-1

I have the following code from Determine if Stdin has data with 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")
    }
}

but no matter how I run it, size is always 0.

I am running Fedora 32 with Go version 1.14

DB Wizz
  • 27
  • 1
  • 1
  • 4
  • how have you tried to run it? – Frank Bryce Jul 24 '20 at 00:18
  • 2
    A pipe doesn’t have a length. If you want to know the size you ha e to read it. – JimB Jul 24 '20 at 00:43
  • @FrankBryce echo 'test me' | go run test.go – DB Wizz Jul 24 '20 at 02:53
  • @FrankBryce why did you remove your answer?! I upvoted it. – DB Wizz Jul 24 '20 at 05:19
  • I didn't.. I wonder if a mod removed it for some reason – Frank Bryce Jul 24 '20 at 12:26
  • 1
    @DBWizz: It doesn't work in your case because there is no standard way to read the size of a named pipe (semantically a pipe has no size, implementations vary by buffer size). Even if you are on a system that returns a size for the pipe, it's only going to report up to the internal buffer size which doesn't tell you the size of the input. – JimB Jul 24 '20 at 13:27
  • @jimB I copied code from the web that others said worked for them. – DB Wizz Jul 25 '20 at 05:01
  • @FrankBryce what is this operator <<< ? – DB Wizz Jul 25 '20 at 05:02
  • @DBWizz: unfortunately not everything published on the internet is correct. `<<<` is a ["here string"](https://www.tldp.org/LDP/abs/html/x17837.html), and it does not necessarily create a pipe. – JimB Jul 27 '20 at 13:41

1 Answers1

-1

You have to compile to code to get an executable. Then you can pipe in any text to it, to get its size.

go build pipe.go
ls -lah pipe
2.1M Jul 23 23:06 pipe

Then you can run it by

echo "test" | ./pipe
5 bytes available in Stdin
Saeed
  • 550
  • 1
  • 7
  • 12