bb/src/tool/cat/cat.go

62 lines
937 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
)
2021-01-28 03:39:37 +03:00
var(
blockSize int
)
2022-02-20 07:02:39 +03:00
func Cat(p string) error {
2020-01-06 10:20:10 +03:00
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 {
2021-01-28 03:39:37 +03:00
b := make([]byte, blockSize)
2020-01-06 10:20:10 +03:00
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
}
func Run(args []string) {
2020-01-06 10:20:10 +03:00
arg0 := args[0]
args = args[1:]
flagSet := flag.NewFlagSet(arg0, flag.ExitOnError)
2021-01-28 03:39:37 +03:00
flagSet.IntVar(&blockSize, "bs", 512, "block size")
flagSet.Usage = func() {
2021-01-28 03:39:37 +03:00
fmt.Fprintf(os.Stderr, "usage: %s [options] [files]\n", 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 {
2022-03-26 21:48:51 +03:00
e := Cat(p)
2020-01-06 10:20:10 +03:00
if e != nil {
fmt.Fprintf(os.Stderr, "%s: %s.\n", arg0, e)
}
}
} else {
fcat(os.Stdin)
2019-10-30 02:54:45 +03:00
}
}