Seek To Fixed Offsets For Record Access

Read arbitrary records from a fixed-width stream with io.Seeker: absolute, relative, and end-relative seeks land exactly on record boundaries.

GoData Integrity

Code

gosnippet
51 lines
package main

import (
	"bytes"
	"fmt"
	"io"
)

const recordSize = 12 // fixed-width record: 8-byte name + 4-byte count

// readAt seeks first and reads one whole record; all three positioning modes funnel here
func readAt(reader io.ReadSeeker, record []byte, whence int, offset int64) {
	if _, err := reader.Seek(offset, whence); err != nil {
		fmt.Println("seek:", err)
		return
	}
	if _, err := io.ReadFull(reader, record); err != nil {
		fmt.Println("read:", err)
		return
	}
	fmt.Printf("  name=%s count=%s\n", string(record[:8]), string(record[8:]))
}

func main() {
	var buf bytes.Buffer
	for _, rec := range [][2]string{
		{"widget-1", "0042"},
		{"widget-2", "0007"},
		{"widget-3", "0100"},
		{"widget-4", "0025"},
	} {
		buf.WriteString(rec[0])
		buf.WriteString(rec[1])
	}

	// bytes.Reader implements io.ReadSeeker, so random-access positioning works
	reader := bytes.NewReader(buf.Bytes())
	record := make([]byte, recordSize)

	// SeekStart: absolute offset = record index × record width
	fmt.Println("record 1:")
	readAt(reader, record, io.SeekStart, int64(recordSize)*1)

	// SeekCurrent: skip one more record from the current position
	fmt.Println("skip one:")
	readAt(reader, record, io.SeekCurrent, int64(recordSize))

	// SeekEnd: a negative offset backs up from the end and grabs the last record
	fmt.Println("last:")
	readAt(reader, record, io.SeekEnd, -int64(recordSize))
}

How the snippet works

Seek To Fixed Offsets For Record Access reduces to the functions readAt and main.

Repetition is confined to for _, rec := range [][2]string — the rest of the file is straight-line. Error handling is inline: 2 places test err != nil and branch immediately.

Applying it

Entry signature: func readAt(reader io.ReadSeeker, record []byte, whence int, offset int64)

The demo output is labeled (seek:, read:, name=), so the printed output reads as a trace of the operations performed.

The demo flow inside main is readAt — run the file to see it end to end.

Statements that carry the weight

for _, rec := range [][2]string{
	{"widget-1", "0042"},
	{"widget-2", "0007"},
	{"widget-3", "0100"},
	{"widget-4", "0025"},
} {
	buf.WriteString(rec[0])
	buf.WriteString(rec[1])
}

Interactive Tools for This Topic

FAQ

What does Seek To Fixed Offsets For Record Access print when run?
No setup needed: run the file and look for labeled lines like `seek:`, `read:`, `name=` in the output.