I am currently dabbling in [GoLang] go-lang and trying to get familiar with it’s syntax and style of programming. I also want to get familiar with the built-in packages for basic tasks witout having to google for basic features.

In this post I will be working my way up to building a simple program that can list the files of a given path to it as a command line argument.

1. Print to console

Lets start with a simple program that can print a statement to the console using the "fmt" package and the "Println()" fucntion.

package main

import (
	"fmt"
)

func main() {
    fmt.Println("Welcome to Go!")
}
#=> Welcome to Go!

2. Read arguments from commandline

Now, lets learn to read the command line arguments to the program using the "os" package and Args variable that stores them as an array of strings starting with the program name as the first element.

package main

import (
	"fmt"
	"os"
)

func main() {
	if len(os.Args) > 1 {
		fmt.Println("Arguments:", os.Args[1])
	} else {
		fmt.Println("No Arguments provided")
	}
}
#=> Apurvas-MacBook-Pro:OSManipulation apurva$ go run CommandLineArgs.go Hello
Arguments: Hello

#=> Apurvas-MacBook-Pro:OSManipulation apurva$ go run CommandLineArgs.go
No Arguments provided

3. Traversing the listings of a path

Finally, we need to be able to discover all the file/directory listings for a given path passed as a command line argument.

This can be conveniently achieved using the ReadDir() function of the "io/ioutil" package


package main

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

func main() {
	var files []os.FileInfo
	var err error
	if len(os.Args) > 1 {
		files, err = ioutil.ReadDir(os.Args[1])
	} else {
		files, err = ioutil.ReadDir(".")
	}

	if err != nil {
		fmt.Println("Err ", err)
	}
	for _, file := range files {
		fmt.Print(file.Mode())
		fmt.Print(" ", file.Size())
		fmt.Print(" ", file.Name())
		fmt.Println()
	}
}

The ReadDir() returns a list of directory entries sorted by filename.

#🤓 Exploring further into "fmt", "os", "io/ioutil" to recreate a implementaion of the "ls" unix utility is left as an exercise for the reader.

PS: Also check out my blog post on recreating "ls" unix utility in [python3.][ls-python3]

ls-python3