Home >Backend Development >Golang >How Can I Get the Total Size of a Windows Drive Using Go?
To retrieve the total size of a drive in Windows using Go, delve into the standard windows API call, specifically the GetDiskFreeSpaceExW() function from kernel32.dll. While this function was previously employed to obtain free space, it also provides access to the drive's total size.
GetDiskFreeSpaceExW() has several parameters:
In your Go code, you can implement this solution as follows:
package main import ( "fmt" "syscall" "unsafe" ) func main() { kernelDLL, err := syscall.LoadDLL("kernel32.dll") if err != nil { fmt.Println("Failed to load kernel32.dll:", err) return } GetDiskFreeSpaceExW, err := kernelDLL.FindProc("GetDiskFreeSpaceExW") if err != nil { fmt.Println("Failed to find GetDiskFreeSpaceExW proc:", err) return } var free, total, avail int64 path := "c:\" r1, r2, _ := GetDiskFreeSpaceExW.Call( uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(path))), uintptr(unsafe.Pointer(&free)), uintptr(unsafe.Pointer(&total)), uintptr(unsafe.Pointer(&avail)), ) fmt.Println("Free:", free, "Total:", total, "Available:", avail) if r1 == 1 && r2 == 0 { fmt.Println("Success.") } else { fmt.Println("Failed:", syscall.Errno(r1)) } }
This code will provide the desired output, displaying both the total and free space on the specified drive.
The above is the detailed content of How Can I Get the Total Size of a Windows Drive Using Go?. For more information, please follow other related articles on the PHP Chinese website!