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

Here, we are going to learn how to get the size of the file using Seek() function in Golang (Go Language)?
Submitted by Nidhi, on April 07, 2021 [Last updated : March 04, 2023]

How to get the size of the file using Seek() function in Golang?

Problem Solution:

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.

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 code to get the size of the file using Seek() function

// 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 fmt, os 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.

Golang File Handling Programs »






Comments and Discussions!

Load comments ↻






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