file.go 1.29 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package file

import (
	"os";
	"syscall";
)

type File struct {
	fd      int64;  // file descriptor number
	name    string; // file name at Open time
}

func newFile(fd int64, name string) *File {
	if fd < 0 {
		return nil
	}
	return &File{fd, name}
}

var (
	Stdin  = newFile(0, "/dev/stdin");
	Stdout = newFile(1, "/dev/stdout");
	Stderr = newFile(2, "/dev/stderr");
)

30
func Open(name string, mode int64, perm int64) (file *File, err os.Error) {
31 32 33 34
	r, e := syscall.Open(name, mode, perm);
	return newFile(r, name), os.ErrnoToError(e)
}

35
func (file *File) Close() os.Error {
36 37 38 39 40 41 42 43
	if file == nil {
		return os.EINVAL
	}
	r, e := syscall.Close(file.fd);
	file.fd = -1;  // so it can't be closed again
	return nil
}

44
func (file *File) Read(b []byte) (ret int, err os.Error) {
45 46 47 48 49 50 51
	if file == nil {
		return -1, os.EINVAL
	}
	r, e := syscall.Read(file.fd, &b[0], int64(len(b)));
	return int(r), os.ErrnoToError(e)
}

52
func (file *File) Write(b []byte) (ret int, err os.Error) {
53 54 55 56 57 58 59 60 61 62
	if file == nil {
		return -1, os.EINVAL
	}
	r, e := syscall.Write(file.fd, &b[0], int64(len(b)));
	return int(r), os.ErrnoToError(e)
}

func (file *File) String() string {
	return file.name
}