From 29419eec3c4d05a894e692a4f722e70fe99af404 Mon Sep 17 00:00:00 2001 From: jienfak Date: Sun, 29 Sep 2019 01:06:14 +0500 Subject: [PATCH] cat: First implementation. --- cat/main.go | 58 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 cat/main.go diff --git a/cat/main.go b/cat/main.go new file mode 100644 index 0000000..d377c4d --- /dev/null +++ b/cat/main.go @@ -0,0 +1,58 @@ +package main + +import( + "fmt" + "os" + "io" + "log" + "flag" +) + +const( + bufSiz = 1024 +) + +func catFile(file *os.File) error { + buf := make([]byte, bufSiz) + for { + n, err := file.Read(buf) + if n>0 { + fmt.Printf("%s", buf[:n]) + } + if err == io.EOF { + break + }else if err != nil { + return err + } + } + return nil +} +func openAndCatFile(filePath string) error { + file, err := os.Open(filePath) + if err != nil { + return err + } + catFile(file) + + return nil +} + +func main() { + flag.Parse() + warn := log.New(os.Stderr, os.Args[0]+": ", 0) + status := 0 + if flag.NArg()>0 { // Files. + for _, pathFile := range flag.Args() { + err := openAndCatFile(pathFile) + if err != nil { + warn.Println(err) + } + } + } else { // Stdin. + err := catFile(os.Stdin) + if err != nil { + warn.Println(err) + } + } + os.Exit(status) +}