Untitled
raw download clone
GO
views 15
,
size 1213 b
package main

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

func main() {
	lineCountFlag := flag.Bool("l", true, "Print the line count")
	byteCountFlag := flag.Bool("c", true, "Print the byte count")
	wordCountFlag := flag.Bool("w", true, "Print the word count")
	flag.Parse()

	// check that the filename positional arguement has been provided.
	if flag.NArg() == 0 {
		flag.Usage()
		os.Exit(1)
	}

	filename := flag.Arg(0)
	// read the entire file into a byte array
	f, err := ioutil.ReadFile(filename)
	if err != nil {
		fmt.Println("error opening file: err:", err)
		os.Exit(1)
	}

	var wordCount, lineCount, byteCount int64
	// loop over each byte in the array
	for _, byte := range f {
		byteCount++
		if byte == '\n' {
			lineCount++
		}
		if unicode.IsSpace(rune(byte)) {
			wordCount++
		}
	}
	wordCount--
	lineCount++

	// Print depending upon the values of the boolean flags...(default = true)
	fmt.Println("Statistics for: ", filename)
	if *wordCountFlag {
		fmt.Println("Word count: ", wordCount)
	}
	if *lineCountFlag {
		fmt.Println("Line count: ", lineCount)
	}
	if *byteCountFlag {
		fmt.Println("Byte count: ", byteCount)
	}
}
close fullscreen
Login or Register to edit or fork this paste. It's free.