main.go (763B)
1 /* 2 Cat concatenates and prints files. 3 If no arguments is given, it reads from the standard input. 4 5 Usage: 6 7 cat [file ...] 8 */ 9 package main 10 11 import ( 12 "fmt" 13 "io" 14 "os" 15 ) 16 17 func main() { 18 if len(os.Args) == 1 { 19 cat(os.Stdin) 20 return 21 } 22 for _, fname := range os.Args[1:] { 23 f, err := os.Open(fname) 24 if err != nil { 25 fmt.Fprintf(os.Stderr, "cat: %v\n", err) 26 os.Exit(1) 27 } 28 if err := cat(f); err != nil { 29 fmt.Fprintf(os.Stderr, "cat: %v\n", err) 30 f.Close() 31 os.Exit(1) 32 } 33 f.Close() 34 } 35 } 36 37 func cat(f *os.File) error { 38 buf := make([]byte, 8192) 39 for { 40 n, err := f.Read(buf) 41 if n == 0 && err == io.EOF { 42 break 43 } 44 if err != nil { 45 return err 46 } 47 _, err = os.Stdout.Write(buf[:n]) 48 if err != nil { 49 return err 50 } 51 } 52 return nil 53 }