Ruan Bekker's Blog

From a Curious mind to Posts on Github

Golang: Reading From Files and Writing to Disk With Arguments

From our Previous Post we wrote a basic golang app that reads the contents of a file and writes it back to disk, but in a static way as we defined the source and destination filenames in the code.

Today we will use arguments to specify what the source and destination filenames should be instead of hardcoding it.

Our Golang Application:

We will be using if statements to determine if the number of arguments provided is as expected, if not, then a usage string should be returned to stdout. Then we will loop through the list of arguments to determine what the values for our source and destination file should be.

Once it completes, it prints out the coice of filenames that was used:

app.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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)
}

Build your application:

1
$ go build app.go

Run your application with no additional arguments to determine the expected behaviour:

1
2
$ ./app
Usage: (-i/--input) 'input_filename' (-o/--output) 'output_file-to-write'

It works as expected, now create a source file, then run the application:

1
$ echo $RANDOM > myfile.txt

Run the application, and in this run, we will set the destination file as newfile.txt:

1
2
3
$ ./app -i myfile.txt -o newfile.txt
File used for reading: myfile.txt
File used for writing: newfile.txt

Checking out the new file:

1
2
$ cat newfile.txt
8568

Comments