"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How do I Get the File Length in Go?

How do I Get the File Length in Go?

Published on 2024-12-15
Browse:724

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

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3