Q:

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

belongs to collection: Golang File Handling Programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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 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 fmtos 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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Golang File Handling Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Golang program to write data into a file in a sing... >>
<< Golang program to read bytes from the file...