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

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




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.