ruanbekker
3/2/2018 - 11:05 AM

Golang: Read File and Write to Disk with Arguments

Golang: Read File and Write to Disk with Arguments

package main

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

var (
    input_filename string
    output_filename string
)

func main() {

    if len(os.Args) < 5 {
        fmt.Printf("Usage: (-i/--input) 'input_filename' (-o/--output) 'output_filename' \n")
        os.Exit(0)
    }

    for i, arg := range os.Args {
        if arg == "-i" || arg == "--input" {
            input_filename = os.Args[i+1]
            }
        if arg == "-o" || arg == "--output" {
            output_filename = os.Args[i+1]
            }
        }

    input_file_content, error := ioutil.ReadFile(input_filename)

    if error != nil {
        panic(error)
    }

    fmt.Println("File used for reading:", input_filename)

    ioutil.WriteFile(output_filename, input_file_content, 0644)
    fmt.Println("File used for writing:", output_filename)
}