Get amount of free disk space using Go

落爺英雄遲暮 提交于 2019-11-28 18:21:00

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

import "syscall"
import "os"

var stat syscall.Statfs_t

wd, err := os.Getwd()

syscall.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):

h := syscall.MustLoadDLL("kernel32.dll")
c := h.MustFindProc("GetDiskFreeSpaceExW")

var freeBytes int64

_, _, err := c.Call(uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(wd))),
    uintptr(unsafe.Pointer(&freeBytes)), nil, nil)

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!