...

/

Reading and Writing Files with Slices

Reading and Writing Files with Slices

This lesson explains in detail how to use a slice for reading and writing to files.

We'll cover the following...

Slices provide the standard-Go way to handle I/O buffers; they are used in the following second version of the function cat, which reads a file in an infinite for-loop (until end-of-file EOF) in a sliced buffer, and writes it to standard output.

Press + to interact
func cat(f *os.File) {
const NBUF = 512
var buf [NBUF]byte
for {
switch nr, err := f.Read(buf[:]); true {
case nr < 0:
fmt.Fprintf(os.Stderr, "cat: error reading: %s\n", err.Error())
os.Exit(1)
case nr == 0: // EOF
return
case nr > 0:
if nw, ew := os.Stdout.Write(buf[0:nr]); nw != nr {
fmt.Fprintf(os.Stderr, "cat: error writing: %s\n")
}
}
}
}

Look at the following example:

Welcome to Educative

Click the RUN button, and wait for the terminal to start. Type go run main.go test.txt and press ENTER.

This program is mostly the ...