3 回答
TA贡献1825条经验 获得超4个赞
您链接的问题+答案显示了如何获得可用空间。该解决方案使用 中的GetDiskFreeSpaceExW()
Windows API 函数来kernel32.dll
获取它。
同样的函数也可以用来获取总大小。函数签名GetDiskFreeSpaceExW()
:
BOOL GetDiskFreeSpaceExW( LPCWSTR lpDirectoryName, PULARGE_INTEGER lpFreeBytesAvailableToCaller, PULARGE_INTEGER lpTotalNumberOfBytes, PULARGE_INTEGER lpTotalNumberOfFreeBytes );
它有一个输入参数,路径,它有 3 个输出参数,即空闲字节数(可供调用者使用)、总字节数(磁盘大小)和总空闲字节数。
因此,只需在您调用它时,为您想要从中获取的所有信息提供变量(指针)。
例如:
kernelDLL := syscall.MustLoadDLL("kernel32.dll")
GetDiskFreeSpaceExW := kernelDLL.MustFindProc("GetDiskFreeSpaceExW")
var free, total, avail int64
path := "c:\\"
r1, r2, lastErr := GetDiskFreeSpaceExW.Call(
uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(path))),
uintptr(unsafe.Pointer(&free)),
uintptr(unsafe.Pointer(&total)),
uintptr(unsafe.Pointer(&avail)),
)
fmt.Println(r1, r2, lastErr)
fmt.Println("Free:", free, "Total:", total, "Available:", avail)
运行它,示例输出:
1 0 Success.
Free: 16795295744 Total: 145545281536 Available: 16795295744
TA贡献1784条经验 获得超2个赞
由于系统调用已弃用,其他回复已过时。
您现在必须使用 golang.org/x/sys/windows:
import (
"fmt"
"golang.org/x/sys/windows"
)
// print disk usage of path/disk
func DiskUsage(path string) bool {
var free, total, avail uint64
path = "c:\\"
pathPtr, err := windows.UTF16PtrFromString(path)
if err != nil{
panic(err)
}
err = windows.GetDiskFreeSpaceEx(pathPtr, &free, &total, &avail)
fmt.Println("Free:", free, "Total:", total, "Available:", avail)
}
TA贡献1865条经验 获得超7个赞
在GetDiskFreeSpraceExW的文档中,该函数声明为:
BOOL GetDiskFreeSpaceExW(
LPCWSTR lpDirectoryName,
PULARGE_INTEGER lpFreeBytesAvailableToCaller,
PULARGE_INTEGER lpTotalNumberOfBytes,
PULARGE_INTEGER lpTotalNumberOfFreeBytes
);
因此,您可以在一次调用中获得总大小和可用大小:
import "syscall"
import "os"
func main() {
wd := os.Getwd()
h := syscall.MustLoadDLL("kernel32.dll")
c := h.MustFindProc("GetDiskFreeSpaceExW")
var freeBytesAvailableToCaller int64
var totalNumberOfBytes int64
var totalNumberOfFreeBytes int64
c.Call(
uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(wd))),
uintptr(unsafe.Pointer(&freeBytesAvailableToCaller)),
uintptr(unsafe.Pointer(&totalNumberOfBytes)),
uintptr(unsafe.Pointer(&totalNumberOfFreeBytes))
)
print(freeBytesAvailableToCaller, totalNumberOfBytes, totalNumberOfBytes)
}
- 3 回答
- 0 关注
- 162 浏览
添加回答
举报