Search code examples
godiskspace

Get amount of free disk space using Go


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.


Solution

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