Q:

Golang program to get the size of the file using Seek() function

0

In this program, we will get the size of the file by seeking a file pointer at end of the file using Seek() function. The Seek() function returns the new located position to the calling function.

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 get the size of the file using Seek() function is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Golang program to get the size of the
// file using Seek() function

package main

import "os"
import "fmt"

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

	//We moved file pointer to end of file.
	size, err := Myfile.Seek(0, 2)
	if err != nil {
		fmt.Println(err)
	}

	fmt.Printf("Size of file is %d bytes\n", size)
	Myfile.Close()
}

Output:

Size of file is 12 bytes

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 opened the "Sample.txt" file and the seek file pointer to the end of the file. The Seek() function returns the new position. Here, we assigned a new position to the size variable that represents the total size of the file in bytes.

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

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now