[Go]Assignment 3: Open a text file and display the content

So here is the assignment 3 for this course Go: The Complete Developer’s Guide (Golang) by Stephen Grider, this assignment is a self research assignment which is why Stephen branded assignment3 as hard mode, this is an assignment to train students on how to read the Go documentation. It is not overly hard but it is a good practice to “appreciate” interface in golang.

I personally still cannot appreciate interface yet, but I have no choice but to try to convince myself interface helps to “reduce” code, to me interface compare with traditional OOP’s inheritance, the OOP’s way makes a lot more sense.

So for this assignment, I need to use the OS package to open and read the file contents, the Read function in OS is an interface which defines that it expect a byte slice argument and return an integer and an error.

To run the code go run main.go myfile.txt as indicated in assignment3.

package main

import (
	"fmt"
	"log"
	"os"
)
/*
The contents of myfile.txt is below:
*****************************************
This is the content of the file.
Try to see if I can use os.Open to open it.
 */
func main() {
	// Open the text file.
	file, err := os.Open("myfile.txt")
	// Check for file open error
	if err != nil {
		log.Fatal("Error:", err)
	}

	// uses the Read interface hence requires a byte slice as argument. 100 bytes is more than enough.
	bs := make([]byte, 100)
	// interested in getting the bytes read and the error if any.
	n, e := file.Read(bs)
	// error checking for read error.
	if e != nil {
		log.Fatal("File read error:", e)
	}
	// print out the bytes read and the contents of myfile.txt
	fmt.Println("Number of bytes read:",n,"\n",string(bs))
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s