From 65f21f805739cf8963da080aca9033be4ca99bd4 Mon Sep 17 00:00:00 2001 From: jienfak Date: Thu, 27 Feb 2020 08:37:41 +0500 Subject: [PATCH] tac: Simplified version implemented. cat: Simplified "Run" function initialization. --- cat/cat.go | 8 +++---- goblin.go | 2 ++ tac/tac.go | 67 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 73 insertions(+), 4 deletions(-) create mode 100644 tac/tac.go diff --git a/cat/cat.go b/cat/cat.go index 5564b33..78330e8 100644 --- a/cat/cat.go +++ b/cat/cat.go @@ -34,11 +34,11 @@ func fcat(f *os.File) error { } func Run(args []string) int { - flagSet := flag.NewFlagSet(args[0], flag.ExitOnError) - flagSet.Parse(args[1:]) + status := 0 arg0 := args[0] args = args[1:] - status := 0 + flagSet := flag.NewFlagSet(arg0, flag.ExitOnError) + flagSet.Parse(args) if len(args)>0 { for _, p := range args { e := cat(p) @@ -50,4 +50,4 @@ func Run(args []string) int { fcat(os.Stdin) } return status -} \ No newline at end of file +} diff --git a/goblin.go b/goblin.go index 71ee4fb..d539a57 100644 --- a/goblin.go +++ b/goblin.go @@ -10,6 +10,7 @@ import( "github.com/jienfak/goblin/gtrue" "github.com/jienfak/goblin/gfalse" "github.com/jienfak/goblin/sort" + "github.com/jienfak/goblin/tac" ) func main() { @@ -26,6 +27,7 @@ func main() { "true" : gtrue.Run, "false" : gfalse.Run, "sort" : sort.Run, + "tac" : tac.Run, } if binBase := path.Base(os.Args[0]) ; binBase != "goblin" { diff --git a/tac/tac.go b/tac/tac.go new file mode 100644 index 0000000..d6efda1 --- /dev/null +++ b/tac/tac.go @@ -0,0 +1,67 @@ +package tac +/* Concatenate files in "stdout" reversed. */ +import( + "os" + "io" + "flag" + "fmt" + "bufio" +) + +func reverse(a []string) chan string { + ret := make(chan string) + go func() { + l := len(a) + for i, _ := range a { + ret <- a[l-1-i] + } + close(ret) + }() + return ret +} + +func tac(p string) error { + f, e := os.Open(p) + if e != nil { + return e + } + defer f.Close() + ftac(f) + return nil +} + + +func ftac(f *os.File) error { + r := bufio.NewReader(os.Stdin) + var lines []string + for { + line, e := r.ReadString('\n') + if e == io.EOF { + break + } + lines = append(lines, line) + } + for l := range reverse(lines) { + fmt.Print(l) + } + return nil +} + +func Run(args []string) int { + status := 0 + arg0 := args[0] + args = args[1:] + flagSet := flag.NewFlagSet(arg0, flag.ExitOnError) + flagSet.Parse(args) + if len(args)>0 { + for _, p := range args { + e := tac(p) + if e != nil { + fmt.Fprintf(os.Stderr, "%s: %s.\n", arg0, e) + } + } + } else { + ftac(os.Stdin) + } + return status +}