Skip to content

Instantly share code, notes, and snippets.

@proudlygeek
Created November 4, 2012 16:02
Show Gist options
  • Save proudlygeek/4012401 to your computer and use it in GitHub Desktop.
Save proudlygeek/4012401 to your computer and use it in GitHub Desktop.
Unix "cat" command in Go
package main
import (
"fmt"
"os"
"io"
"log"
"io/ioutil"
)
//
// This script implements the unix cat.
//
func cat(r io.Reader) ([]byte, error) {
data, err := ioutil.ReadAll(r);
if (err != nil) {
return nil, err
}
return data, nil
}
func main() {
var output []byte
var err error
args := os.Args[1:]
if len(args) > 0 {
for _, file := range args {
data, err := os.Open(file)
defer data.Close()
if err != nil {
log.Panic(err)
}
output, err = cat(data)
if err != nil {
log.Panic(err)
}
fmt.Print(string(output))
}
} else {
output, err = cat(os.Stdin)
if err != nil {
log.Panic(err)
}
fmt.Print(string(output))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment