github.com/mvdan/u-root-coreutils@v0.0.0-20230122170626-c2eef2898555/cmds/core/cat/cat.go (about) 1 // Copyright 2012-2017 the u-root Authors. All rights reserved 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // cat concatenates files and prints them to stdout. 6 // 7 // Synopsis: 8 // 9 // cat [-u] [FILES]... 10 // 11 // Description: 12 // 13 // If no files are specified, read from stdin. 14 // 15 // Options: 16 // 17 // -u: ignored flag 18 package main 19 20 import ( 21 "flag" 22 "fmt" 23 "io" 24 "log" 25 "os" 26 ) 27 28 var _ = flag.Bool("u", false, "ignored") 29 30 func cat(reader io.Reader, writer io.Writer) error { 31 if _, err := io.Copy(writer, reader); err != nil { 32 return fmt.Errorf("error concatenating stdin to stdout: %v", err) 33 } 34 return nil 35 } 36 37 func run(args []string, stdin io.Reader, stdout io.Writer) error { 38 if len(args) == 0 { 39 if err := cat(stdin, stdout); err != nil { 40 return fmt.Errorf("error concatenating stdin to stdout: %v", err) 41 } 42 } 43 for _, file := range args { 44 if file == "-" { 45 err := cat(stdin, stdout) 46 if err != nil { 47 return err 48 } 49 continue 50 } 51 f, err := os.Open(file) 52 if err != nil { 53 return err 54 } 55 if err := cat(f, stdout); err != nil { 56 return fmt.Errorf("failed to concatenate file %s to given writer", f.Name()) 57 } 58 f.Close() 59 } 60 return nil 61 } 62 63 func main() { 64 flag.Parse() 65 if err := run(flag.Args(), os.Stdin, os.Stdout); err != nil { 66 log.Fatalf("cat failed with: %v", err) 67 } 68 }