Golang How to read input filename in Go

Matt picture Matt · Jan 29, 2016 · Viewed 8k times · Source

I would like to run my go file on my input.txt where my go program will read the input.txt file when I type in go run command ie:

go run goFile.go input.txt

I don't want to put input.txt in my goFile.go code since my go file should run on any input name not just input.txt.

I try ioutil.ReadAll(os.Stdin) but I need to change my command to

go run goFile.go < input.txt

I only use package fmt, os, bufio and io/ioutil. Is it possible to do it without any other packages?

Answer

icza picture icza · Jan 29, 2016

Please take a look at the package documentation of io/ioutil which you are already using.

It has a function exactly for this: ReadFile()

func ReadFile(filename string) ([]byte, error)

Example usage:

func main() {
    // First element in os.Args is always the program name,
    // So we need at least 2 arguments to have a file name argument.
    if len(os.Args) < 2 {
        fmt.Println("Missing parameter, provide file name!")
        return
    }
    data, err := ioutil.ReadFile(os.Args[1])
    if err != nil {
        fmt.Println("Can't read file:", os.Args[1])
        panic(err)
    }
    // data is the file content, you can use it
    fmt.Println("File content is:")
    fmt.Println(string(data))
}