To read a fixed number of bytes from a bufio.Reader in Go, you can use the Read
function along with a byte slice of the desired size.
Here's an example:
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
file, err := os.Open("file.txt")
if err != nil {
fmt.Println("Error opening file:", err)
return
}
defer file.Close()
reader := bufio.NewReader(file)
numBytes := 10 // Specify the number of bytes to read
buffer := make([]byte, numBytes)
n, err := reader.Read(buffer)
if err != nil {
fmt.Println("Error reading file:", err)
return
}
fmt.Printf("Read %d bytes: %s\n", n, buffer)
}
In this example, we open a file and create a bufio.Reader
to read from it. We then specify the number of bytes to read (numBytes
) and create a buffer with the same size. Finally, we use the Read
function to read the specified number of bytes into the buffer.
Note that the Read
function returns the number of bytes read (n
) and any error encountered during the read operation (err
). You can handle the error accordingly.
Make sure to replace "file.txt"
with the actual file path you want to read from.