January 2018
Intermediate to advanced
340 pages
8h 6m
English
Another useful function provided by the io package is io.ReadAtLeast(). This will return an error if at least specific number of bytes are not. Similar to io.ReadFull(), an EOF error is returned if no data is found, and an ErrUnexpectedEOF error is returned if some data is read before encountering the end of the file:
package main import ( "io" "log" "os" ) func main() { // Open file for reading file, err := os.Open("test.txt") if err != nil { log.Fatal(err) } byteSlice := make([]byte, 512) minBytes := 8 // io.ReadAtLeast() will return an error if it cannot // find at least minBytes to read. It will read as // many bytes as byteSlice can hold. numBytesRead, err := io.ReadAtLeast(file, byteSlice, minBytes) if err != ...Read now
Unlock full access