How to get file length in Go?

FileGo

File Problem Overview


I looked up golang.org/pkg/os/#File , but still have no idea. Seems there is no way to get file length, did I miss something?

How to get file length in Go?

File Solutions


Solution 1 - File

(*os.File).Stat() returns a os.FileInfo value, which in turn has a Size() method. So, given a file f, the code would be akin to

fi, err := f.Stat()
if err != nil {
  // Could not obtain stat, handle error
}

fmt.Printf("The file is %d bytes long", fi.Size())

Solution 2 - File

If you don't want to open the file, you can directly call os.Stat instead.

fi, err := os.Stat("/path/to/file")
if err != nil {
    return err
}
// get the size
size := fi.Size()

Solution 3 - File

Slightly more verbose answer:

file, err := os.Open( filepath ) 
if err != nil {
	log.Fatal(err)
}
fi, err := file.Stat()
if err != nil {
 	log.Fatal(err)
}
fmt.Println( fi.Size() )

Solution 4 - File

Calling os.Stat as sayed by @shebaw (at least in UNIX OS) is more efficient, cause stat() is a Unix system call that returns file attributes about an inode, and is not necessary to deal with open the file.

NOTE: Using other method can lead to too many open files in multithread/concurrency application, due to the fact that you open the file for query the stats

Here the benchmark

func GetFileSize1(filepath string) (int64, error) {
	fi, err := os.Stat(filepath)
	if err != nil {
		return 0, err
	}
	// get the size
	return fi.Size(), nil
}

func GetFileSize2(filepath string) (int64, error) {
	f, err := os.Open(filepath)
	if err != nil {
		return 0, err
	}
	defer f.Close()
	fi, err := f.Stat()
	if err != nil {
		return 0, err
	}
	return fi.Size(), nil
}
BenchmarkGetFileSize1-8           704618              1662 ns/op
BenchmarkGetFileSize2-8           199461              5668 ns/op

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhardPassView Question on Stackoverflow
Solution 1 - FileDominik HonnefView Answer on Stackoverflow
Solution 2 - FileshebawView Answer on Stackoverflow
Solution 3 - FileLonnie WebbView Answer on Stackoverflow
Solution 4 - FilealessiosaviView Answer on Stackoverflow