Reading Files
// Importing necessary packages.
import (
"bufio"
"fmt"
"io"
"os"
)
// Function to check for errors and panic if an error is encountered.
func check(e error) {
if e != nil {
panic(e)
}
}
// The main function, where the execution of the program begins.
func main() {
// Reading the entire contents of the file using os.ReadFile.
dat, err := os.ReadFile("/tmp/dat")
check(err)
fmt.Print(string(dat))
// Opening the file for further reading.
f, err := os.Open("/tmp/dat")
check(err)
// Reading the first 5 bytes from the file.
b1 := make([]byte, 5)
n1, err := f.Read(b1)
check(err)
fmt.Printf("%d bytes: %s\n", n1, string(b1[:n1]))
// Seeking to a specific position (offset 6) in the file and reading 2 bytes.
o2, err := f.Seek(6, 0)
check(err)
b2 := make([]byte, 2)
n2, err := f.Read(b2)
check(err)
fmt.Printf("%d bytes @ %d: %v\n", n2, o2, string(b2[:n2]))
// Performing another seek and reading at least 2 bytes into a buffer.
o3, err := f.Seek(6, 0)
check(err)
b3 := make([]byte, 2)
n3, err := io.ReadAtLeast(f, b3, 2)
check(err)
fmt.Printf("%d bytes @ %d: %s\n", n3, o3, string(b3))
// Seeking back to the beginning of the file.
_, err = f.Seek(0, 0)
check(err)
// Using a buffered reader to peek at the first 5 bytes without consuming them.
r4 := bufio.NewReader(f)
b4, err := r4.Peek(5)
check(err)
fmt.Printf("5 bytes: %s\n", string(b4))
// Closing the file.
f.Close()
}output
Last updated