Created
November 4, 2012 16:02
-
-
Save proudlygeek/4012401 to your computer and use it in GitHub Desktop.
Unix "cat" command in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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