diff src/tac.go @ 0:de451fa0c9cd

golang repository.
author pyon@macmini
date Sat, 01 Oct 2016 11:16:31 +0900
parents
children
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/tac.go	Sat Oct 01 11:16:31 2016 +0900
@@ -0,0 +1,49 @@
+package main
+
+import (
+    "bufio"
+    "flag"
+    "fmt"
+    "os"
+)
+
+func main() {
+    flag.Parse()
+
+    files := flag.Args()
+
+    var lines []string
+
+    // Input
+    if len( files ) == 0 {
+        lines = ReverseLines( os.Stdin, nil )
+    } else {
+        for _, arg := range files {
+            f, err := os.Open( arg )
+            if err != nil {
+                fmt.Fprintf( os.Stderr, "tac : %v\n", err )
+                continue
+            }
+            l := ReverseLines( f, nil )
+            f.Close()
+            lines = append( lines, l... )
+        }
+    }
+
+    // Output
+    for _, line := range lines {
+        fmt.Println( line )
+    }
+}
+
+func ReverseLines( f *os.File, l []string ) []string {
+    input := bufio.NewScanner( f )
+    for input.Scan() {
+        l = append( l, input.Text() )
+    }
+    for i, j := 0, len(l) - 1; i < j; i, j = i + 1, j - 1 {
+        l[i], l[j] = l[j], l[i]
+    }
+    return l
+}
+