Read file using fseek or seek in golang

File Reading Using Seek() in golang

In Golang there are multiple way to read a text file, but most of the file operation are done in in-memory, but when its come to very large file, in that case we need to read the file chunk by chunk. Similar to fseek in c or c++, in golang we have Seek function.

Using Seek function we can use golang to read n bytes from file.

Seek function is member function of os.Open(), Eg: when we open the file after that by using Seek function, we have option to read the file from begin, or current or from the end.

fseek in go

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. 

Go Code to read File:


package main

import (

func main() {

	file, err := os.Open("fileForTest.txt")
	if err != nil {
	defer file.Close()
	for {
		o2, err := file.Seek(0, 1)
		if err != nil {
		b1 := make([]byte, 20)
		n1, err := file.Read(b1)
		if err != nil {
			log.Fatal("Failed here ", err)
		fmt.Printf("start:%d %d bytes: %s\n", o2, n1, string(b1))


Post a Comment