使用 Go 获取可用磁盘空间量
基本上我想要 df -h
的输出,其中包括可用空间和卷的总大小.该解决方案需要在 Windows、Linux 和 Mac 上运行,并使用 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.
我浏览了 os
和 syscall
Go 文档,但没有找到任何东西.在 Windows 上,即使是命令行实用程序也很笨拙(dir C:
)或需要提升权限(fsutil volume diskfree C:
).当然有一种方法可以做到这一点,我还没有找到......
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...
更新:
根据 nemo 的回答和邀请,我提供了一个 跨平台 Go 包来执行此操作.
在 POSIX 系统上,您可以使用 sys.unix.Statfs
.
以字节为单位打印当前工作目录的可用空间示例:
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))
对于 Windows,您还需要使用系统调用路由.示例(源,更新以匹配 新的 sys/windows
包):
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"
h := windows.MustLoadDLL("kernel32.dll")
c := h.MustFindProc("GetDiskFreeSpaceExW")
var freeBytes int64
_, _, err := c.Call(uintptr(unsafe.Pointer(windows.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.