[Go]Capture user’s entered sentence and save into a file.

This extends the previous post about capturing user’s input. The captured input is stored into a file known as text.txt.

To write a string to a file ioutil.WriteFile is used, this method requires three arguments:

  1. filename in string
  2. string byte slice, which is the ascii representation of the string slice
  3. The permission, if unsure check the linux file permission basic
package main

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

func main() {
	// set up the stream reader
	reader := bufio.NewReader(os.Stdin)
	fmt.Println("Enter a sentence or word, the word will be stored as text.txt")
	// txt is the string captured from stdin after an enter is pressed (\n)
	// the txt also stores the delimiter.
	if txt, err := reader.ReadString('\n'); err != nil {
		// if error print out error reason and exit.
		fmt.Println("There is an error:", err)
		os.Exit(1)
	} else {
		// WriteFile requires these arguments: filename in string, string byte slice, and permission.
		// 0644 is Owner is able to read and write, while group and others can read.
		// r = 4, w = 2, x = 1, if 6 means 4+2 = rw, if 4 means r only.
		// if 7 means rwx = 4+2+1, linux file permission basics.
		if err := ioutil.WriteFile("text.txt", []byte(txt), 0644); err != nil {
			fmt.Println("Write file error:", err)
			os.Exit(1)
		}
	}
}

Result
w1w2

For the permission I have an old post which explains the permission representation.

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