使用 Go 获取可用磁盘空间量 [英] Get amount of free disk space using Go

查看:97
本文介绍了使用 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.

我浏览了 ossyscall 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.

这篇关于使用 Go 获取可用磁盘空间量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆