Graham Slick
Graham Slick

Reputation: 6870

Read file at byte location

I need to read a file at a specific location, given by a byte offset.

filePath := "test_file.txt"
byteOffset := 6
// Read file

How can I achieve this, if possible without reading the whole file in memory ?

Upvotes: 1

Views: 1116

Answers (1)

peterSO
peterSO

Reputation: 166935

Package os

import "os"

func (*File) Seek

func (f *File) Seek(offset int64, whence int) (ret int64, err error)

Seek sets the offset for the next Read or Write on file to offset, interpreted according to whence: 0 means relative to the origin of the file, 1 means relative to the current offset, and 2 means relative to the end. It returns the new offset and an error, if any. The behavior of Seek on a file opened with O_APPEND is not specified.


Package io

import "io" 

Seek whence values.

const (
    SeekStart   = 0 // seek relative to the origin of the file
    SeekCurrent = 1 // seek relative to the current offset
    SeekEnd     = 2 // seek relative to the end 
)

For example,

package main

import (
    "fmt"
    "io"
    "os"
)

func main() {
    filePath := "test.file"
    byteOffset := 6
    f, err := os.Open(filePath)
    if err != nil {
        panic(err)
    }
    defer f.Close()
    _, err = f.Seek(int64(byteOffset), io.SeekStart)
    if err != nil {
        panic(err)
    }
    buf := make([]byte, 16)
    n, err := f.Read(buf[:cap(buf)])
    buf = buf[:n]
    if err != nil {
        if err != io.EOF {
            panic(err)
        }
    }
    fmt.Printf("%s\n", buf)
}

Output:

$ cat test.file
0123456789
$ go run seek.go
6789

$

Upvotes: 4

Related Questions