Get amount of free disk space using Go
Asked Answered
Y

3

48

Basically I want the output of df -h, which includes both the free space and the total size of the volume. The solution needs to work on Windows, Linux, and Mac and be written in Go.

I have looked through the os and syscall Go documentation and haven't found anything. On Windows, even command line utils are either awkward (dir C:\) or need elevated privileges (fsutil volume diskfree C:\). Surely there is a way to do this that I haven't found yet...

UPDATE:
Per nemo's answer and invitation, I have provided a cross-platform Go package that does this.

Yusem answered 20/11, 2013 at 22:33 Comment(1)
All I've got is that you could drop to C with cgo: write freespace_windows.go and freespace_{linux,bsd}.go, and use GetDiskFreeSpace and statvfs to get free space.Lisette
B
78

On POSIX systems you can use sys.unix.Statfs.
Example of printing free space in bytes of current working directory:

import "golang.org/x/sys/unix"
import "os"

var stat unix.Statfs_t

wd, err := os.Getwd()

unix.Statfs(wd, &stat)

// Available blocks * size per block = available space in bytes
fmt.Println(stat.Bavail * uint64(stat.Bsize))

For Windows you need to go the syscall route as well. Example (source, updated to match new sys/windows package):

import "golang.org/x/sys/windows"

var freeBytesAvailable uint64
var totalNumberOfBytes uint64
var totalNumberOfFreeBytes uint64

err := windows.GetDiskFreeSpaceEx(windows.StringToUTF16Ptr("C:"),
    &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes)

Feel free to write a package that provides the functionality cross-platform. On how to implement something cross-platform, see the build tool help page.

Borosilicate answered 21/11, 2013 at 1:39 Comment(8)
Thanks for the detailed post. I have updated my question to include the link to my package that does this.Yusem
Do you know the difference between stat.Bavail and stat.Bfree? Documented here: golang.org/pkg/syscall/#Statfs_tLorinalorinda
@Lorinalorinda Bavail is the amount of blocks available to unprivileged users. Bfree is simply the total number of free blocks.Borosilicate
"On POSIX systems you can use syscall.Statfs" Unfortunatly this isn't a POSIX compliant syscall. The POSIX compliant call is "statvfs". Statfs gives different information on different *NIX OS'es. Why the Go makers choose to implement the non-POSIX compliant version is beyond me.Alt
gives me error: 'wd' unexpected in line wd, err := os.Getwd()Tolbert
From the package docs: "Deprecated: this package is locked down. Callers should use the corresponding package in the golang.org/x/sys repository instead. golang.org/pkg/syscall/#StatfsKatsuyama
@BrettHolman quite right, updated the answerBorosilicate
I think there is a typo in the declaration of freeBytes: int64 should be uint64, no?Volin
B
11

Here is my version of the df -h command based on github.com/shirou/gopsutil library

package main

import (
    "fmt"

    human "github.com/dustin/go-humanize"
    "github.com/shirou/gopsutil/disk"
)

func main() {
    formatter := "%-14s %7s %7s %7s %4s %s\n"
    fmt.Printf(formatter, "Filesystem", "Size", "Used", "Avail", "Use%", "Mounted on")

    parts, _ := disk.Partitions(true)
    for _, p := range parts {
        device := p.Mountpoint
        s, _ := disk.Usage(device)

        if s.Total == 0 {
            continue
        }

        percent := fmt.Sprintf("%2.f%%", s.UsedPercent)

        fmt.Printf(formatter,
            s.Fstype,
            human.Bytes(s.Total),
            human.Bytes(s.Used),
            human.Bytes(s.Free),
            percent,
            p.Mountpoint,
        )
    }
}

Beano answered 30/9, 2020 at 15:59 Comment(1)
This works very well on Windows 10 and MacOS 11.3. Thank you.Pollute
C
9

Minio has a package (GoDoc) to show disk usage that is cross platform, and seems to be well maintained:

import (
        "github.com/minio/minio/pkg/disk"
        humanize "github.com/dustin/go-humanize"
)

func printUsage(path string) error {
        di, err := disk.GetInfo(path)
        if err != nil {
            return err
        }
        percentage := (float64(di.Total-di.Free)/float64(di.Total))*100
        fmt.Printf("%s of %s disk space used (%0.2f%%)\n", 
            humanize.Bytes(di.Total-di.Free), 
            humanize.Bytes(di.Total), 
            percentage,
        )
}
Carper answered 8/6, 2020 at 2:19 Comment(3)
This code is actually provides data from output of du -h e.g. directory usage instead of requested df -h command providing a disk usage. Anyway It may be a good example of using minio package.Beano
go: module github.com/minio/minio@upgrade found (v0.0.0-20230424202818-8fd07bcd51cf), but does not contain package github.com/minio/minio/pkg/diskMarion
The package is now github.com/minio/minio/internal/disk and cannot be used.Garrido

© 2022 - 2024 — McMap. All rights reserved.