Documentation
¶
Overview ¶
Package io provides basic interfaces to I/O primitives. Its primary job is to wrap existing implementations of such primitives, such as those in package os, into shared public interfaces that abstract the functionality, plus some other related primitives.
Because these interfaces and primitives wrap lower-level operations with various implementations, unless otherwise informed clients should not assume they are safe for parallel execution.
Index ¶
- Constants
- Variables
- func Copy(dst Writer, src Reader) (written int64, err error)
- func CopyBuffer(dst Writer, src Reader, buf []byte) (written int64, err error)
- func CopyN(dst Writer, src Reader, n int64) (written int64, err error)
- func Pipe() (*PipeReader, *PipeWriter)
- func ReadAll(r Reader) ([]byte, error)
- func ReadAtLeast(r Reader, buf []byte, min int) (n int, err error)
- func ReadFull(r Reader, buf []byte) (n int, err error)
- func WriteString(w Writer, s string) (n int, err error)
- type ByteReader
- type ByteScanner
- type ByteWriter
- type Closer
- type LimitedReader
- type OffsetWriter
- type PipeReader
- type PipeWriter
- type ReadCloser
- type ReadSeekCloser
- type ReadSeeker
- type ReadWriteCloser
- type ReadWriteSeeker
- type ReadWriter
- type Reader
- type ReaderAt
- type ReaderFrom
- type RuneReader
- type RuneScanner
- type SectionReader
- type Seeker
- type StringWriter
- type WriteCloser
- type WriteSeeker
- type Writer
- type WriterAt
- type WriterTo
Examples ¶
Constants ¶
const ( SeekStart = 0 // seek relative to the origin of the file SeekCurrent = 1 // seek relative to the current offset SeekEnd = 2 // seek relative to the end )
Seek whence values.
Variables ¶
var EOF = errors.New("EOF")
EOF is the error returned by Read when no more input is available. (Read must return EOF itself, not an error wrapping EOF, because callers will test for EOF using ==.) Functions should return EOF only to signal a graceful end of input. If the EOF occurs unexpectedly in a structured data stream, the appropriate error is either ErrUnexpectedEOF or some other error giving more detail.
var ErrClosedPipe = errors.New("io: read/write on closed pipe")
ErrClosedPipe is the error used for read or write operations on a closed pipe.
var ErrNoProgress = errors.New("multiple Read calls return no data or error")
ErrNoProgress is returned by some clients of a Reader when many calls to Read have failed to return any data or error, usually the sign of a broken Reader implementation.
var ErrShortBuffer = errors.New("short buffer")
ErrShortBuffer means that a read required a longer buffer than was provided.
var ErrShortWrite = errors.New("short write")
ErrShortWrite means that a write accepted fewer bytes than requested but failed to return an explicit error.
var ErrUnexpectedEOF = errors.New("unexpected EOF")
ErrUnexpectedEOF means that EOF was encountered in the middle of reading a fixed-size block or data structure.
Functions ¶
func Copy ¶
Copy copies from src to dst until either EOF is reached on src or an error occurs. It returns the number of bytes copied and the first error encountered while copying, if any.
A successful Copy returns err == nil, not err == EOF. Because Copy is defined to read from src until EOF, it does not treat an EOF from Read as an error to be reported.
If src implements the WriterTo interface, the copy is implemented by calling src.WriteTo(dst). Otherwise, if dst implements the ReaderFrom interface, the copy is implemented by calling dst.ReadFrom(src).
Example ¶
package main
import (
"io"
"log"
"os"
"strings"
)
func main() {
r := strings.NewReader("some io.Reader stream to be read\n")
if _, err := io.Copy(os.Stdout, r); err != nil {
log.Fatal(err)
}
}
Output: some io.Reader stream to be read
func CopyBuffer ¶ added in go1.5
CopyBuffer is identical to Copy except that it stages through the provided buffer (if one is required) rather than allocating a temporary one. If buf is nil, one is allocated; otherwise if it has zero length, CopyBuffer panics.
If either src implements WriterTo or dst implements ReaderFrom, buf will not be used to perform the copy.
Example ¶
package main
import (
"io"
"log"
"os"
"strings"
)
func main() {
r1 := strings.NewReader("first reader\n")
r2 := strings.NewReader("second reader\n")
buf := make([]byte, 8)
// buf is used here...
if _, err := io.CopyBuffer(os.Stdout, r1, buf); err != nil {
log.Fatal(err)
}
// ... reused here also. No need to allocate an extra buffer.
if _, err := io.CopyBuffer(os.Stdout, r2, buf); err != nil {
log.Fatal(err)
}
}
Output: first reader second reader
func CopyN ¶
CopyN copies n bytes (or until an error) from src to dst. It returns the number of bytes copied and the earliest error encountered while copying. On return, written == n if and only if err == nil.
If dst implements the ReaderFrom interface, the copy is implemented using it.
Example ¶
package main
import (
"io"
"log"
"os"
"strings"
)
func main() {
r := strings.NewReader("some io.Reader stream to be read")
if _, err := io.CopyN(os.Stdout, r, 4); err != nil {
log.Fatal(err)
}
}
Output: some
func Pipe ¶
func Pipe() (*PipeReader, *PipeWriter)
Pipe creates a synchronous in-memory pipe. It can be used to connect code expecting an io.Reader with code expecting an io.Writer.
Reads and Writes on the pipe are matched one to one except when multiple Reads are needed to consume a single Write. That is, each Write to the PipeWriter blocks until it has satisfied one or more Reads from the PipeReader that fully consume the written data. The data is copied directly from the Write to the corresponding Read (or Reads); there is no internal buffering.
It is safe to call Read and Write in parallel with each other or with Close. Parallel calls to Read and parallel calls to Write are also safe: the individual calls will be gated sequentially.
Example ¶
package main
import (
"fmt"
"io"
"log"
"os"
)
func main() {
r, w := io.Pipe()
go func() {
fmt.Fprint(w, "some io.Reader stream to be read\n")
w.Close()
}()
if _, err := io.Copy(os.Stdout, r); err != nil {
log.Fatal(err)
}
}
Output: some io.Reader stream to be read
func ReadAll ¶ added in go1.16
ReadAll reads from r until an error or EOF and returns the data it read. A successful call returns err == nil, not err == EOF. Because ReadAll is defined to read from src until EOF, it does not treat an EOF from Read as an error to be reported.
Example ¶
package main
import (
"fmt"
"io"
"log"
"strings"
)
func main() {
r := strings.NewReader("Go is a general-purpose language designed with systems programming in mind.")
b, err := io.ReadAll(r)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s", b)
}
Output: Go is a general-purpose language designed with systems programming in mind.
func ReadAtLeast ¶
ReadAtLeast reads from r into buf until it has read at least min bytes. It returns the number of bytes copied and an error if fewer bytes were read. The error is EOF only if no bytes were read. If an EOF happens after reading fewer than min bytes, ReadAtLeast returns ErrUnexpectedEOF. If min is greater than the length of buf, ReadAtLeast returns ErrShortBuffer. On return, n >= min if and only if err == nil. If r returns an error having read at least min bytes, the error is dropped.
Example ¶
package main
import (
"fmt"
"io"
"log"
"strings"
)
func main() {
r := strings.NewReader("some io.Reader stream to be read\n")
buf := make([]byte, 14)
if _, err := io.ReadAtLeast(r, buf, 4); err != nil {
log.Fatal(err)
}
fmt.Printf("%s\n", buf)
// buffer smaller than minimal read size.
shortBuf := make([]byte, 3)
if _, err := io.ReadAtLeast(r, shortBuf, 4); err != nil {
fmt.Println("error:", err)
}
// minimal read size bigger than io.Reader stream
longBuf := make([]byte, 64)
if _, err := io.ReadAtLeast(r, longBuf, 64); err != nil {
fmt.Println("error:", err)
}
}
Output: some io.Reader error: short buffer error: unexpected EOF
func ReadFull ¶
ReadFull reads exactly len(buf) bytes from r into buf. It returns the number of bytes copied and an error if fewer bytes were read. The error is EOF only if no bytes were read. If an EOF happens after reading some but not all the bytes, ReadFull returns ErrUnexpectedEOF. On return, n == len(buf) if and only if err == nil. If r returns an error having read at least len(buf) bytes, the error is dropped.
Example ¶
package main
import (
"fmt"
"io"
"log"
"strings"
)
func main() {
r := strings.NewReader("some io.Reader stream to be read\n")
buf := make([]byte, 4)
if _, err := io.ReadFull(r, buf); err != nil {
log.Fatal(err)
}
fmt.Printf("%s\n", buf)
// minimal read size bigger than io.Reader stream
longBuf := make([]byte, 64)
if _, err := io.ReadFull(r, longBuf); err != nil {
fmt.Println("error:", err)
}
}
Output: some error: unexpected EOF
func WriteString ¶
WriteString writes the contents of the string s to w, which accepts a slice of bytes. If w implements StringWriter, its WriteString method is invoked directly. Otherwise, w.Write is called exactly once.
Example ¶
package main
import (
"io"
"log"
"os"
)
func main() {
if _, err := io.WriteString(os.Stdout, "Hello World"); err != nil {
log.Fatal(err)
}
}
Output: Hello World
Types ¶
type ByteReader ¶
ByteReader is the interface that wraps the ReadByte method.
ReadByte reads and returns the next byte from the input or any error encountered. If ReadByte returns an error, no input byte was consumed, and the returned byte value is undefined.
ReadByte provides an efficient interface for byte-at-time processing. A Reader that does not implement ByteReader can be wrapped using bufio.NewReader to add this method.
type ByteScanner ¶
type ByteScanner interface {
ByteReader
UnreadByte() error
}
ByteScanner is the interface that adds the UnreadByte method to the basic ReadByte method.
UnreadByte causes the next call to ReadByte to return the last byte read. If the last operation was not a successful call to ReadByte, UnreadByte may return an error, unread the last byte read (or the byte prior to the last-unread byte), or (in implementations that support the Seeker interface) seek to one byte before the current offset.
type ByteWriter ¶ added in go1.1
ByteWriter is the interface that wraps the WriteByte method.
type Closer ¶
type Closer interface {
Close() error
}
Closer is the interface that wraps the basic Close method.
The behavior of Close after the first call is undefined. Specific implementations may document their own behavior.
type LimitedReader ¶
A LimitedReader reads from R but limits the amount of data returned to just N bytes. Each call to Read updates N to reflect the new amount remaining. Read returns EOF when N <= 0 or when the underlying R returns EOF.
type OffsetWriter ¶ added in go1.20
type OffsetWriter struct {
// contains filtered or unexported fields
}
An OffsetWriter maps writes at offset base to offset base+off in the underlying writer.
func NewOffsetWriter ¶ added in go1.20
func NewOffsetWriter(w WriterAt, off int64) *OffsetWriter
NewOffsetWriter returns an OffsetWriter that writes to w starting at offset off.