Sling Academy
Home/Golang/Go: How to get the size of a file (in KB or mB)

Go: How to get the size of a file (in KB or mB)

Last updated: November 26, 2024

When working with file systems in Go, one of the common tasks you may encounter is retrieving the size of a file. Knowing the file size can be crucial for applications that require storage limits or bandwidth allocations. In this article, we'll guide you through steps and code examples to obtain the size of a file, convert it into kilobytes (KB) or megabytes (MB), and print the results in Go.

Using the os package

Go provides the os package, which offers many utilities to work with files, including a method to get file information. Here's how you can use it:

Step 1: Import the Required Package

First, import the necessary packages:

import (
    "fmt"
    "os"
)

Step 2: Retrieve File Info

Use the os.Stat() function to retrieve file information. It returns a struct containing the file's size and other data:

func getFileSize(filePath string) int64 {
    fileInfo, err := os.Stat(filePath)
    if err != nil {
        fmt.Println(err)
        return 0
    }
    return fileInfo.Size()
}

Step 3: Convert Size to KB and MB

The file size returned is in bytes, so you'll need to convert it:

func main() {
    filePath := "path/to/your/file.txt"

    // Get the size in bytes
    fileSizeBytes := getFileSize(filePath)
    fmt.Println("File size in Bytes:", fileSizeBytes)

    // Convert to KB
    fileSizeKB := float64(fileSizeBytes) / 1024
    fmt.Printf("File size in KB: %.2f
", fileSizeKB)

    // Convert to MB
    fileSizeMB := fileSizeKB / 1024
    fmt.Printf("File size in MB: %.2f
", fileSizeMB)
}

Complete Example

Here is the complete Go program to get the file size:

package main

import (
    "fmt"
    "os"
)

func getFileSize(filePath string) int64 {
    fileInfo, err := os.Stat(filePath)
    if err != nil {
        fmt.Println("Error:", err)
        return 0
    }
    return fileInfo.Size()
}

func main() {
    filePath := "path/to/your/file.txt"

    // Get the size in bytes
    fileSizeBytes := getFileSize(filePath)
    fmt.Println("File size in Bytes:", fileSizeBytes)

    // Convert to KB
    fileSizeKB := float64(fileSizeBytes) / 1024
    fmt.Printf("File size in KB: %.2f\n", fileSizeKB)

    // Convert to MB
    fileSizeMB := fileSizeKB / 1024
    fmt.Printf("File size in MB: %.2f\n", fileSizeMB)
}

By following these steps, you can easily obtain and convert the file size in Go applications. This approach ensures that you effectively manage file resources within your application and can report sizes in the most useful units.

Next Article: How to delete one or multiple files in Go

Previous Article: Go: How to get filename & extension from a path

Series: File I/O and Operating System Interaction

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant