cat: Code simplified.

This commit is contained in:
jienfak 2020-01-06 12:20:10 +05:00
parent f1fd751b48
commit 3d0fc73832

View file

@ -1,70 +1,53 @@
package cat
/* Simple module to get output of a few files
* and put in in one only. */
/* Concatenate files in "stdout". */
import(
"os"
"io"
"log"
"flag"
"fmt"
)
type Catter struct {
warn *log.Logger
out *os.File
bufSiz int
buf []byte
func cat(p string) error {
f, e := os.Open(p)
if e != nil {
return e
}
defer f.Close()
fcat(f)
return nil
}
func New(out *os.File, warn *log.Logger, bufSiz int) *Catter {
c := new(Catter)
c.out = out
c.warn = warn
c.bufSiz = bufSiz
c.buf = make([]byte, c.bufSiz)
return c
}
func (c Catter) Cat(files []*os.File) error {
for _, file := range files {
for {
n, err := file.Read(c.buf)
if n>0 {
_, err := c.out.Write(c.buf[:n])
if err != nil {
return err
}
}
if err == io.EOF {
break
}else if err != nil {
c.warn.Println(err)
}
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
}
}
return nil
}
func (c Catter)OpenArr(filePaths []string) []*os.File {
files := make([]*os.File, len(filePaths))
for i, filePath := range filePaths {
var err error
files[i], err = os.Open(filePath)
if err != nil {
c.warn.Println(err)
}
}
return files
}
func Run(args []string) int {
func Run(args []string) int {
flagSet := flag.NewFlagSet(args[0], flag.ExitOnError)
flagSet.Parse(args[1:])
arg0 := args[0]
args = 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
if len(args)>0 {
for _, p := range args {
e := cat(p)
if e != nil {
fmt.Fprintf(os.Stderr, "%s: %s.\n", arg0, e)
}
}
} else {
fcat(os.Stdin)
}
return status
}