tac: Simplified version implemented.

cat: Simplified "Run" function initialization.
This commit is contained in:
jienfak 2020-02-27 08:37:41 +05:00
parent 010d8f8f4e
commit 65f21f8057
3 changed files with 73 additions and 4 deletions

View file

@ -34,11 +34,11 @@ func fcat(f *os.File) error {
} }
func Run(args []string) int { func Run(args []string) int {
flagSet := flag.NewFlagSet(args[0], flag.ExitOnError) status := 0
flagSet.Parse(args[1:])
arg0 := args[0] arg0 := args[0]
args = args[1:] args = args[1:]
status := 0 flagSet := flag.NewFlagSet(arg0, flag.ExitOnError)
flagSet.Parse(args)
if len(args)>0 { if len(args)>0 {
for _, p := range args { for _, p := range args {
e := cat(p) e := cat(p)

View file

@ -10,6 +10,7 @@ import(
"github.com/jienfak/goblin/gtrue" "github.com/jienfak/goblin/gtrue"
"github.com/jienfak/goblin/gfalse" "github.com/jienfak/goblin/gfalse"
"github.com/jienfak/goblin/sort" "github.com/jienfak/goblin/sort"
"github.com/jienfak/goblin/tac"
) )
func main() { func main() {
@ -26,6 +27,7 @@ func main() {
"true" : gtrue.Run, "true" : gtrue.Run,
"false" : gfalse.Run, "false" : gfalse.Run,
"sort" : sort.Run, "sort" : sort.Run,
"tac" : tac.Run,
} }
if binBase := path.Base(os.Args[0]) ; binBase != "goblin" { if binBase := path.Base(os.Args[0]) ; binBase != "goblin" {

67
tac/tac.go Normal file
View file

@ -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
}