mc.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Command mc prints in multiple columns.
  2. //
  3. // Usage: mc [-] [-N] [file...]
  4. //
  5. // Mc splits the input into as many columns as will fit in N
  6. // print positions. If the output is a tty, the default N is
  7. // the number of characters in a terminal line; otherwise the
  8. // default N is 80. Under option - each input line ending in
  9. // a colon ':' is printed separately.
  10. package main
  11. import (
  12. "github.com/kr/pty"
  13. "github.com/kr/text/colwriter"
  14. "io"
  15. "log"
  16. "os"
  17. "strconv"
  18. )
  19. func main() {
  20. var width int
  21. var flag uint
  22. args := os.Args[1:]
  23. for len(args) > 0 && len(args[0]) > 0 && args[0][0] == '-' {
  24. if len(args[0]) > 1 {
  25. width, _ = strconv.Atoi(args[0][1:])
  26. } else {
  27. flag |= colwriter.BreakOnColon
  28. }
  29. args = args[1:]
  30. }
  31. if width < 1 {
  32. _, width, _ = pty.Getsize(os.Stdout)
  33. }
  34. if width < 1 {
  35. width = 80
  36. }
  37. w := colwriter.NewWriter(os.Stdout, width, flag)
  38. if len(args) > 0 {
  39. for _, s := range args {
  40. if f, err := os.Open(s); err == nil {
  41. copyin(w, f)
  42. f.Close()
  43. } else {
  44. log.Println(err)
  45. }
  46. }
  47. } else {
  48. copyin(w, os.Stdin)
  49. }
  50. }
  51. func copyin(w *colwriter.Writer, r io.Reader) {
  52. if _, err := io.Copy(w, r); err != nil {
  53. log.Println(err)
  54. }
  55. if err := w.Flush(); err != nil {
  56. log.Println(err)
  57. }
  58. }