You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
68 lines
1.0 KiB
Go
68 lines
1.0 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"flag"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
)
|
|
|
|
func byteCounter(f *os.File) {
|
|
fileInfo, err := f.Stat()
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "error: %v\n", err)
|
|
os.Exit(1)
|
|
}
|
|
fmt.Println(fileInfo.Size())
|
|
}
|
|
|
|
func lineCounter(f io.Reader) {
|
|
buf := make([]byte, 32*1024)
|
|
count := 0
|
|
lineSep := []byte{'\n'}
|
|
|
|
for {
|
|
c, err := f.Read(buf)
|
|
count += bytes.Count(buf[:c], lineSep)
|
|
|
|
switch {
|
|
case err == io.EOF:
|
|
fmt.Println(count)
|
|
return
|
|
|
|
case err != nil:
|
|
fmt.Fprintf(os.Stderr, "error: %v\n", err)
|
|
os.Exit(1)
|
|
}
|
|
}
|
|
}
|
|
|
|
func main() {
|
|
|
|
cFlag := flag.Bool("c", false, "print the byte counts")
|
|
lFlag := flag.Bool("l", false, "print the line counts")
|
|
flag.Parse()
|
|
fileName := flag.Arg(0)
|
|
|
|
if len(fileName) == 0 {
|
|
fmt.Fprintf(os.Stderr, "gowc [flags] filename\n")
|
|
flag.Usage()
|
|
os.Exit(1)
|
|
}
|
|
|
|
f, err := os.Open(fileName)
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "error: %v\n", err)
|
|
os.Exit(1)
|
|
}
|
|
defer f.Close()
|
|
|
|
switch {
|
|
case *cFlag:
|
|
byteCounter(f)
|
|
case *lFlag:
|
|
lineCounter(f)
|
|
}
|
|
}
|