答案 0 :(得分:4)
您链接的问题+答案显示了如何获得可用空间。该解决方案使用kernel32.dll
中的GetDiskFreeSpaceExW()
Windows API函数来获取它。
相同的函数也可以用于获取总大小。 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
答案 1 :(得分:2)
在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)
}
答案 2 :(得分:1)
由于不赞成syscall,其他答复已过时。
您现在必须使用golang.org/x/sys/windows(适应icza答案):
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)
}