×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang program to demonstrate the Seek() function to random access from the file

Here, we are going to demonstrate the Seek() function to random access from the file in Golang (Go Language)?
Submitted by Nidhi, on April 07, 2021 [Last updated : March 04, 2023]

Seek() function in Golang

Problem Solution:

In this program, we will read data from a file randomly using Seek() function. The Seek() function accepts two arguments offset and whence.

Offset - It is used to specify the number of bytes to move in the backward or forward direction.

Whence - It specifies from where we want to move the file pointer.

  • 0 - From the beginning of the file
  • 1 - From the current position
  • 0 - From End of file

Program/Source Code:

The source code to demonstrate the Seek() function to random access from the file is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

Golang code to demonstrate the example of Seek() function to random access from the file

// Golang program to demonstrate the Seek() function
// to random access from the file

package main

import "os"
import "fmt"

func main() {
	Myfile, err := os.Open("Sample.txt")
	if err != nil {
		fmt.Println("Error opening file!!!")
	}

	byteBuff := make([]byte, 11)
	totalLen, err := Myfile.Read(byteBuff)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Printf("File Data: \n%s\n", string(byteBuff[:totalLen]))

	//We move file pointer 3 bytes before from current position.
	newPosition, err := Myfile.Seek(-5, 1)
	if err != nil {
		fmt.Println(err)
	}

	byteBuff1 := make([]byte, 5)
	totalLen1, err1 := Myfile.Read(byteBuff1)
	if err1 != nil {
		fmt.Println(err1)
	}
	fmt.Printf("File Data from position %d is: \n%s\n", newPosition, string(byteBuff1[:totalLen1]))

	Myfile.Close()
}

Output:

File Data: 
Hello World
File Data from position 6 is: 
World

Explanation:

In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the fmt, os packages then we can use a function related to the fmt and os package.

In the main() function, we read 11 bytes from the existing "Sample.txt" file and then move file pointer 5 bytes in backward direction using Seek() function and then again read 5 bytes from the file and print on the console screen.

Golang File Handling Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.