×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang os.SEEK_CUR Constant with Examples

Golang | os.SEEK_CUR Constant: Here, we are going to learn about the SEEK_CUR constant of the os package with its usages, syntax, and examples.
Submitted by IncludeHelp, on October 26, 2021

os.SEEK_CUR

In the Go language, the os package provides a platform-independent interface to operating system (Unix-like) functionality. The SEEK_CUR constant is used to seek relative to the current offset i.e., it specifies the current position of the file pointer, it is used with the Seek() function to seek the file pointer at the given position from the current position of the file pointer.

The value of SEEK_CUR constant 1.

Syntax

SEEK_CUR int

Implementation in the package source code:

SEEK_CUR int = 1

Parameters

  • None

Return Value

The return type of the os.SEEK_CUR constant is an int, it returns 1 i.e., the value of SEEK_CUR constant is 1.

Example 1

// Golang program to demonstrate the
// example of SEEK_CUR constant

package main

import (
	"fmt"
	"os"
)

func main() {
	// Printing the type and value
	fmt.Printf("Type of os.SEEK_CUR: %T\n",
		os.SEEK_CUR)
	fmt.Printf("Value of os.SEEK_CUR: %d\n",
		os.SEEK_CUR)
}

Output:

Type of os.SEEK_CUR: int
Value of os.SEEK_CUR: 1

Example 2

// Golang program to demonstrate the
// example of SEEK_CUR constant

package main

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

func check(e error) {
	if e != nil {
		panic(e)
	}
}

func main() {
	// Write the data to the file
	f, err := os.Create("file1.txt")
	check(err)

	defer f.Close()

	data := []byte("Hello, world!")
	n2, err := f.Write(data)
	check(err)
	fmt.Printf("Wrote %d bytes\n", n2)
	defer f.Close()

	// Read the data from the file
	f, err = os.Open("file1.txt")
	check(err)
	defer f.Close()

	filedata := make([]byte, 15)
	n1, err := f.Read(filedata)
	check(err)
	fmt.Printf("File data: %d bytes: %s\n", n1, string(filedata[:n1]))

	// Seeking to start i.e., at 0th position
	// from current and read the content
	f.Seek(-13, os.SEEK_CUR)
	n1, err = io.ReadAtLeast(f, filedata, 5)
	check(err)
	fmt.Printf("File data: %d bytes: %s\n", n1, string(filedata[:n1]))

	// Seeking to 6th position from the current
	// and read the content
	f.Seek(-6, os.SEEK_CUR)
	n1, err = io.ReadAtLeast(f, filedata, 5)
	check(err)
	fmt.Printf("File data: %d bytes: %s\n", n1, string(filedata[:n1]))
}

Output:

Wrote 13 bytes
File data: 13 bytes: Hello, world!
File data: 13 bytes: Hello, world!
File data: 6 bytes: world!

Golang os Package »




Comments and Discussions!

Load comments ↻





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