Added support for c and l flags
parent
9efb6926ab
commit
b5619c98d6
@ -0,0 +1,3 @@
|
||||
module gitea.paas.celticinfo.fr/oabrivard/gowc
|
||||
|
||||
go 1.21.3
|
||||
@ -0,0 +1,67 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue