tac.go 895 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package tac
  2. /* Concatenate files in "stdout" reversed. */
  3. import(
  4. "os"
  5. "io"
  6. "fmt"
  7. "bufio"
  8. "surdeus.su/core/cli/mtool"
  9. )
  10. func reverse(a []string) chan string {
  11. ret := make(chan string)
  12. go func() {
  13. l := len(a)
  14. for i, _ := range a {
  15. ret <- a[l-1-i]
  16. }
  17. close(ret)
  18. }()
  19. return ret
  20. }
  21. func tac(p string) error {
  22. f, e := os.Open(p)
  23. if e != nil {
  24. return e
  25. }
  26. defer f.Close()
  27. ftac(f)
  28. return nil
  29. }
  30. func ftac(f *os.File) error {
  31. r := bufio.NewReader(f)
  32. var lines []string
  33. for {
  34. line, e := r.ReadString('\n')
  35. if e == io.EOF {
  36. break
  37. }
  38. lines = append(lines, line)
  39. }
  40. for l := range reverse(lines) {
  41. fmt.Print(l)
  42. }
  43. return nil
  44. }
  45. func Run(flagSet *mtool.Flags) {
  46. flagSet.Parse()
  47. args := flagSet.Args()
  48. if len(args)>0 {
  49. for _, p := range args {
  50. e := tac(p)
  51. if e != nil {
  52. fmt.Fprintf(os.Stderr, "%s.\n", e)
  53. }
  54. }
  55. } else {
  56. ftac(os.Stdin)
  57. }
  58. }