Home >Backend Development >Golang >How Do I Determine the Length of a File in Go?

How Do I Determine the Length of a File in Go?

Barbara Streisand
Barbara StreisandOriginal
2024-11-18 07:58:02718browse

How Do I Determine the Length of  a File in Go?

Determining File Length in Go

Go programmers looking to obtain the length of a file may be initially puzzled, as the standard library's os.File type doesn't include a dedicated method for this purpose.

Solution: Utilize Stat() and Size()

The solution lies in the Stat() method of the os.File type. This method returns an os.FileInfo value, which provides access to a variety of file attributes, including its size through the Size() method.

For instance, consider the following code snippet:

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

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

In this code, f represents an open file. Calling Stat() on f retrieves the corresponding os.FileInfo struct, denoted by fi. The Size() method of fi can then be invoked to acquire the file length, which is returned as an integer (number of bytes).

The above is the detailed content of How Do I Determine the Length of a File in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn