From 51f746907b5cb167f22875678a1920e944541e12 Mon Sep 17 00:00:00 2001 From: Meutel Date: Fri, 7 Jul 2017 14:46:40 +0200 Subject: [PATCH] Improved cat --- .gitignore | 1 + go-cat2/main.go | 54 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 go-cat2/main.go diff --git a/.gitignore b/.gitignore index 5ea5040..a6b6ed8 100644 --- a/.gitignore +++ b/.gitignore @@ -28,3 +28,4 @@ avatar/avatar w1d2ex1/w1d2ex1 swap/swap w1d1ex2/w1d1ex2 +go-cat2/go-cat2 diff --git a/go-cat2/main.go b/go-cat2/main.go new file mode 100644 index 0000000..863674c --- /dev/null +++ b/go-cat2/main.go @@ -0,0 +1,54 @@ +package main + +import "fmt" +import "io" +import "log" +import "os" +import "strings" + +var err error +var reader io.Reader + +const BUFSIZE = 32 * 1024 + +func openFile(path *string) *os.File { + f, err := os.Open(os.Args[1]) + if err != nil { + log.Fatalln(err) + } + return f +} + +func readMe(r io.Reader) { + var n int + buf := make([]byte, BUFSIZE) + for { + n, err = r.Read(buf) + if n == 0 || err == io.EOF { + break + } + if err != nil { + log.Fatalln("Read error", err) + } + fmt.Printf("%s", buf[:n]) + } +} + +func main() { + if len(os.Args) <= 1 { + var content string + if _, err := fmt.Scanln(&content); err != nil { + log.Fatalln(err) + } + reader = strings.NewReader(content) + } else { + readers := []io.Reader{} + for i := 1; i < len(os.Args); i++ { + f := openFile(&os.Args[i]) + defer f.Close() + readers = append(readers, f) + } + reader = io.MultiReader(readers...) + } + readMe(reader) +}