io.SectionReader.ReadAt() Function in Golang with Examples
Last Updated :
03 May, 2020
In Go language, io packages supply fundamental interfaces to the I/O primitives. And its principal job is to enclose the ongoing implementations of such king of primitives. The SectionReader.ReadAt() function in Go language is used to return the number of bytes as read by NewSectionReader method. This method holds a buffer and offsets as its parameters. Moreover, this function is defined under the io package. Here, you need to import the “io” package in order to use these functions.
Syntax:
func (s *SectionReader) ReadAt(p []byte, off int64) (n int, err error)
Here, “s” is a pointer to the SectionReader which is returned by the NewSectionReader method, “p” is a buffer of stated byte length, and “off” is the offset of type int64 from where the reading starts.
Return value: It returns the number of bytes of the content returned from the stated buffer of specified length as well as offset and also returns an error if any but if no error occurred then “nil” is returned.
Below examples illustrates the use of above method:
Example 1:
package main
import (
"fmt"
"io"
"strings"
)
func main() {
reader := strings.NewReader( "GeeksforGeeks\n" )
r := io.NewSectionReader(reader, 6, 12)
buf := make([]byte, 4)
n, err := r.ReadAt(buf, 2)
if err != nil {
panic(err)
}
fmt.Printf( "Content in buffer: %s\n" , buf)
fmt.Printf( "n: %v\n" , n)
}
|
Output:
Content in buffer: Geek
n: 4
In the above example first, content is returned from the NewSectionReader() then that content is read from the given offset in the ReadAt() method till the number of bytes stated in the buffer. Then the number of bytes of the resultant content is returned as output here. Moreover, the content of the buffer above has only 4 bytes so, “4” is returned and there is no error thrown while reading the stated content so the error is “nil”.
Example 2:
package main
import (
"fmt"
"io"
"strings"
)
func main() {
reader := strings.NewReader( "Computer Science!" )
r := io.NewSectionReader(reader, 6, 12)
buf := make([]byte, 10)
n, err := r.ReadAt(buf, 2)
if err != nil {
panic(err)
}
fmt.Printf( "Content in buffer: %s\n" , buf)
fmt.Printf( "n: %v\n" , n)
}
|
Output:
panic: EOF
goroutine 1 [running]:
main.main()
/tmp/sandbox798260752/prog.go:31 +0x263
Here, the content in the buffer used in the above code has fewer bytes than stated so, EOF error is thrown.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...