doubaolan2842 2016-01-29 08:38
浏览 277
已采纳

Golang如何在Go中读取输入文件名

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?

  • 写回答

3条回答 默认 最新

  • doulouxun6756 2016-01-29 08:43
    关注

    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))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?