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