Input file using command line?

Hi, a total beginner here. I am wondering how to input a text file using command line?

Like in Python, I could type “python3 program.py < input-file.txt” in the command line to run program with the input text file, is it also possible in Go?

I was trying to use bufio to get some input and it works, but wondering how I can do it in the way I just wrote if it is possible in Go.

Thanks in advance!

1 Like

Yes, it is possible to read from stdin in go.

Just use os.Stdin as the buffer for any of the buffer accepting functions.

3 Likes

Here is an example.

$ cat stdin.go
package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {
    s := bufio.NewScanner(os.Stdin)
    for s.Scan() {
	    b := s.Bytes()
	    fmt.Println(string(b))
    }
    if err := s.Err(); err != nil {
	    fmt.Println(err)
    }
}

$ cat stdin.file
This is data from a file.

.

$ go build stdin.go

$ ./stdin < stdin.file
This is  from a file.

$ cat stdin.file | ./stdin
This is data from a file.
1 Like

Thank you so much!

Thank you! :smiley:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.