Home  >  Article  >  Backend Development  >  How do I Get the File Length in Go?

How do I Get the File Length in Go?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-23 11:54:18615browse

How do I Get the File Length in Go?

Determining File Length in Go

In Go, the os.File type provides a straightforward method for retrieving the length of a file handled by the File pointer.

Retrieval Process

To determine the length of a file, you can leverage the Stat function provided by the os package:

  1. Obtain the os.FileInfo value for the file you wish to inspect. This can be achieved using the Stat function on the file object, like so:
fi, err := f.Stat()
  1. If the Stat function encounters any issues while retrieving the file metadata, the error value returned should be examined and handled accordingly.
  2. Once you have the os.FileInfo value, utilize the Size method to obtain the length of the file in bytes:
fmt.Printf("The file is %d bytes long", fi.Size())

Example Code

To illustrate the retrieval process, consider the following code snippet:

package main

import (
    "fmt"
    "os"
)

func main() {
    f, err := os.Open("my_file.txt")
    if err != nil {
        fmt.Println("Could not open file:", err)
        return
    }

    fi, err := f.Stat()
    if err != nil {
        fmt.Println("Could not obtain file info:", err)
        return
    }

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

By executing this code, you can retrieve and display the length of the specified file, "my_file.txt."

The above is the detailed content of How do I Get the File Length 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