Skip to content

Instantly share code, notes, and snippets.

Created September 10, 2011 06:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save anonymous/1207994 to your computer and use it in GitHub Desktop.
Save anonymous/1207994 to your computer and use it in GitHub Desktop.
Go and CoffeeScript examples of writing a file to stdout
fs = require 'fs'
class File
constructor: (@name) ->
read: (cb) ->
fs.readFile @name, (err, code) ->
throw err if err
cb code.toString()
file = new File "file.txt"
file.read (contents) ->
console.log contents
package main
import (
"fmt"
"os"
"syscall"
)
type File struct {
fd int // file descriptor number
name string // file name at Open time
}
func OpenFile(name string, mode int, perm uint32) (file *File, err os.Error) {
r, e := syscall.Open(name, mode, perm)
if e != 0 {
err = os.Errno(e)
}
return newFile(r, name), err
}
const (
O_RDONLY = syscall.O_RDONLY
O_RDWR = syscall.O_RDWR
O_CREATE = syscall.O_CREAT
O_TRUNC = syscall.O_TRUNC
)
func Open(name string) (file *File, err os.Error) {
return OpenFile(name, O_RDONLY, 0)
}
func (file *File) Close() os.Error {
if file == nil {
return os.EINVAL
}
e := syscall.Close(file.fd)
file.fd = -1 // so it can't be closed again
if e != 0 {
return os.Errno(e)
}
return nil
}
func (file *File) Read(b []byte) (ret int, err os.Error) {
if file == nil {
return -1, os.EINVAL
}
r, e := syscall.Read(file.fd, b)
if e != 0 {
err = os.Errno(e)
}
return int(r), err
}
func (file *File) Write(b []byte) (ret int, err os.Error) {
if file == nil {
return -1, os.EINVAL
}
r, e := syscall.Write(file.fd, b)
if e != 0 {
err = os.Errno(e)
}
return int(r), err
}
func (file *File) String() string {
return file.name
}
func newFile(fd int, name string) *File {
if fd < 0 {
return nil
}
return &File{fd, name}
}
var (
Stdin = newFile(syscall.Stdin, "/dev/stdin")
Stdout = newFile(syscall.Stdout, "/dev/stdout")
Stderr = newFile(syscall.Stderr, "/dev/stderr")
)
func cat(f *File) {
const NBUF = 512
var buf [NBUF]byte
for {
switch nr, er := f.Read(buf[:]); true {
case nr < 0:
fmt.Fprintf(os.Stderr, "cat: error reading from %s: %s\n", f.String(), er.String())
os.Exit(1)
case nr == 0: // EOF
return
case nr > 0:
if nw, ew := Stdout.Write(buf[0:nr]); nw != nr {
fmt.Fprintf(os.Stderr, "cat: error writing from %s: %s\n", f.String(), ew.String())
os.Exit(1)
}
}
}
}
func main() {
f, err := Open("file.txt")
if f == nil {
fmt.Fprintf(os.Stderr, "cat: can't open %s: error %s\n", "file.txt", err)
os.Exit(1)
}
cat(f)
f.Close()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment