bb/cat/cat.go

60 lines
904 B
Go
Raw Normal View History

2019-10-05 12:53:55 +03:00
package cat
2020-01-06 10:20:10 +03:00
/* Concatenate files in "stdout". */
2019-10-05 12:53:55 +03:00
import(
"os"
"io"
2019-10-30 02:54:45 +03:00
"flag"
2020-01-06 10:20:10 +03:00
"fmt"
2019-10-05 12:53:55 +03:00
)
2020-01-06 10:20:10 +03:00
func cat(p string) error {
f, e := os.Open(p)
if e != nil {
return e
2019-10-05 12:53:55 +03:00
}
2020-01-06 10:20:10 +03:00
defer f.Close()
fcat(f)
2019-10-30 02:54:45 +03:00
return nil
2019-10-05 12:53:55 +03:00
}
2020-01-06 10:20:10 +03:00
func fcat(f *os.File) error {
b := make([]byte, 512)
for {
n, e := f.Read(b)
if n>0 {
fmt.Print(string(b[:n]))
}
if e == io.EOF {
break
}else if e != nil {
return e
2019-10-05 12:53:55 +03:00
}
}
2020-01-06 10:20:10 +03:00
return nil
2019-10-30 02:54:45 +03:00
}
2020-01-06 10:20:10 +03:00
func Run(args []string) int {
status := 0
2020-01-06 10:20:10 +03:00
arg0 := args[0]
args = args[1:]
flagSet := flag.NewFlagSet(arg0, flag.ExitOnError)
flagSet.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage of %s: %s [files]\n", arg0, arg0)
flagSet.PrintDefaults()
}
flagSet.Parse(args)
args = flagSet.Args()
2020-01-06 10:20:10 +03:00
if len(args)>0 {
for _, p := range args {
e := cat(p)
if e != nil {
fmt.Fprintf(os.Stderr, "%s: %s.\n", arg0, e)
status = 1
2020-01-06 10:20:10 +03:00
}
}
} else {
fcat(os.Stdin)
2019-10-30 02:54:45 +03:00
}
return status
}