bb/cat/cat.go

70 lines
1.2 KiB
Go
Raw Normal View History

2019-10-05 12:53:55 +03:00
package cat
/* Simple module to get output of a few files
* and put in in one only. */
import(
"os"
"io"
"log"
2019-10-30 02:54:45 +03:00
"flag"
2019-10-05 12:53:55 +03:00
)
type Catter struct {
2019-10-30 02:54:45 +03:00
warn *log.Logger
out *os.File
bufSiz int
2019-10-05 12:53:55 +03:00
buf []byte
}
2019-10-30 02:54:45 +03:00
func New(out *os.File, warn *log.Logger, bufSiz int) *Catter {
2019-10-05 12:53:55 +03:00
c := new(Catter)
2019-10-30 02:54:45 +03:00
c.out = out
2019-10-05 12:53:55 +03:00
c.warn = warn
c.bufSiz = bufSiz
2019-10-30 02:54:45 +03:00
c.buf = make([]byte, c.bufSiz)
2019-10-05 12:53:55 +03:00
return c
}
2019-10-30 02:54:45 +03:00
func (c Catter) Cat(files []*os.File) error {
for _, file := range files {
2019-10-05 12:53:55 +03:00
for {
2019-10-30 02:54:45 +03:00
n, err := file.Read(c.buf)
2019-10-05 12:53:55 +03:00
if n>0 {
2019-10-30 02:54:45 +03:00
_, err := c.out.Write(c.buf[:n])
if err != nil {
return err
}
2019-10-05 12:53:55 +03:00
}
if err == io.EOF {
break
}else if err != nil {
c.warn.Println(err)
}
}
}
2019-10-30 02:54:45 +03:00
return nil
2019-10-05 12:53:55 +03:00
}
2019-10-30 02:54:45 +03:00
func (c Catter)OpenArr(filePaths []string) []*os.File {
files := make([]*os.File, len(filePaths))
2019-10-05 12:53:55 +03:00
for i, filePath := range filePaths {
2019-10-30 02:54:45 +03:00
var err error
files[i], err = os.Open(filePath)
2019-10-05 12:53:55 +03:00
if err != nil {
c.warn.Println(err)
}
}
return files
2019-10-30 02:54:45 +03:00
}
func Run(args []string) int {
flagSet := flag.NewFlagSet(args[0], flag.ExitOnError)
flagSet.Parse(args[1:])
status := 0
warn := log.New(os.Stderr, args[0]+": ", 0)
c := New(os.Stdout, warn, 512)
files := c.OpenArr(flagSet.Args())
err := c.Cat(files)
if err != nil {
status = 1
}
return status
2019-10-05 12:53:55 +03:00
}