Golang – Write sentence to file

This recipe demonstrates how to use flag to build a command line program, how to convert string slice to string and how to write sentence to file specified by user.

Usage example: writefile -f test.txt hi this is a test.

package main

import (
	"flag"
	"io"
	"log"
	"os"
	"strings"
)

func convertSliceToString(s []string) string {
	// Convert string slice to string
	return strings.Join(s, " ")
}

func writeFile(f, txt string) error {
	file, e := os.OpenFile(f, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
	if e != nil {
		return e
	}
	defer file.Close()
	_, wrErr := io.WriteString(file, txt)
	if wrErr != nil {
		return wrErr
	}
	file.Sync()
	return nil
}

func main() {
	filename := flag.String("f", "", "specify file name")
	flag.Parse()
	// flag.Args() returns string slice.
	txt := convertSliceToString(flag.Args())
	e := writeFile(*filename, txt)
	if e != nil {
		log.Fatal(e)
	}
}

Advertisement

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 )

Facebook photo

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

Connecting to %s