Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get total size of a drive in Windows

Tags:

windows

go

I want to get total size of a drive in Go on windows using standard windows api call;

I found this to get the free space.

Now I want to total space size of special drive for example

C:\

like image 997
Zola Man Avatar asked Jan 27 '23 17:01

Zola Man


1 Answers

Your linked question+answer shows how to get the free space. The solution uses the GetDiskFreeSpaceExW() windows API function from the kernel32.dll to obtain it.

The same function can be used to get total size too. Signature of the GetDiskFreeSpaceExW() function:

BOOL GetDiskFreeSpaceExW(
  LPCWSTR         lpDirectoryName,
  PULARGE_INTEGER lpFreeBytesAvailableToCaller,
  PULARGE_INTEGER lpTotalNumberOfBytes,
  PULARGE_INTEGER lpTotalNumberOfFreeBytes
);

It has an in-parameter, the path, and it has 3 out-parameters, namely the free bytes (available to caller), the total bytes (disk size) and the total free bytes.

So simply when you call it, provide variables (pointers) for all info you want to get out of it.

For example:

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)

Running it, an example output:

1 0 Success.
Free: 16795295744 Total: 145545281536 Available: 16795295744
like image 113
icza Avatar answered Jan 29 '23 05:01

icza