DEV Community

Kohei
Kohei

Posted on

Go tutorial: 1. Command Line Arguments and File I/O

This article was originally published on GitHub.

Setup

$ go get golang.org/x/tools/cmd/goimports
...
$ mkdir go-handson
$ cd go-handson

Enter fullscreen mode Exit fullscreen mode

Hello World

$ touch hello.go
Enter fullscreen mode Exit fullscreen mode
// hello.go
package main

import (
    "fmt"
)

func main() {
    fmt.Println("Hello World!")
}
Enter fullscreen mode Exit fullscreen mode
$ $GOPATH/bin/goimports -w .
# Format and add packages that should be imported

$ go run hello.go
Hello World!

$ go build -o hello .

$ ./hello
Hello World!
Enter fullscreen mode Exit fullscreen mode

flag package

Usage of flag.StringVar

$ touch flag.go
Enter fullscreen mode Exit fullscreen mode
// flag.go
package main

import (
    "flag"
    "fmt"
)

func main() {
    var name string
    flag.StringVar(&name, "opt", "", "Usage")

    flag.Parse()

    fmt.Println(name)
}
Enter fullscreen mode Exit fullscreen mode
$ go run hello.go -opt option
option
Enter fullscreen mode Exit fullscreen mode

If you want to know more about the flag package, please go to the https://golang.org/pkg/flag/

Exercise 1-1

Create a CLI application which outputs Hello World! if no options are specified. And if a string option is specified as -name, it has to output Hello [YOUR_NAME]!

$ go run hello.go
Hello World!

$ go run hello.go -name Gopher
Hello Gopher!
Enter fullscreen mode Exit fullscreen mode

The answer is hello.go

os package

Usage of os.Args

$ touch args.go
Enter fullscreen mode Exit fullscreen mode
// args.go
package main

import (
    "fmt"
    "os"
)

func main() {
    fmt.Println(os.Args)
    fmt.Println(os.Args[1])
}
Enter fullscreen mode Exit fullscreen mode
$ go build -o args args.go 
$ ./args Gopher
[./args Gopher]
Gopher
Enter fullscreen mode Exit fullscreen mode

File I/O

Reading files

file, err := os.Open(`/path/to/file`)
if err != nil {
    panic(err)
}
defer file.Close()

buf := make([]byte, BUFSIZE)
for {
    n, err := file.Read(buf)
    if n == 0 {
        break
    }
    if err != nil {
        panic(err)
    }

    fmt.Print(string(buf[:n]))
}
Enter fullscreen mode Exit fullscreen mode

Writing files

f, err := os.Create("/path/to/file")
if err != nil {
    panic(err)
}
defer f.Close()

b := []byte("Foo")
n, err := f.Write(b)
if err != nil {
    panic(err)
}
fmt.Println(n)
Enter fullscreen mode Exit fullscreen mode

Exercise 1-2

Create an application file.go which creates a file and write a string Hello Writing to Files! to it. And the file name has to be specified as a command line argument.

$ go run file.go file.txt
The number of bytes written:  23

$ cat file.txt
Hello Writing to Files!
Enter fullscreen mode Exit fullscreen mode

The answer is file.go

NEXT

Top comments (1)

Collapse
 
wchr profile image
Wachira • Edited

Could you put your go tutorial in a series for ease of access, it's proving hard even with the part naming scheme.