Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang How to read input filename in Go

Tags:

file

go

readfile

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?

like image 504
Matt Avatar asked Jan 29 '16 08:01

Matt


2 Answers

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))
}
like image 68
icza Avatar answered Oct 05 '22 23:10

icza


Firs you check for the provided argument. If the first argument satisfy the condition of an input file, then you use the ioutil.ReadFile method, providing parameter the os.Args result.

package main

import (
    "fmt"
    "os"
    "io/ioutil"
)

func main() {
    if len(os.Args) < 1 {
        fmt.Println("Usage : " + os.Args[0] + " file name")
        os.Exit(1)
    }

    file, err := ioutil.ReadFile(os.Args[1])
    if err != nil {
        fmt.Println("Cannot read the file")
        os.Exit(1)
    }
    // do something with the file
    fmt.Print(string(file))
}

Another possibility is to use:

f, err := os.Open(os.Args[0])

but for this you need to provide the bytes lenght to read:

b := make([]byte, 5) // 5 is the length
n, err := f.Read(b)
fmt.Printf("%d bytes: %s\n", n, string(b))
like image 30
Endre Simo Avatar answered Oct 05 '22 23:10

Endre Simo