Home > Backend Development > Golang > How Can I Get the Total Size of a Windows Drive Using Go?

How Can I Get the Total Size of a Windows Drive Using Go?

Barbara Streisand
Release: 2024-11-19 22:39:02
Original
555 people have browsed it

How Can I Get the Total Size of a Windows Drive Using Go?

Determining the Total Size of a Drive in Windows 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.

Decoding the GetDiskFreeSpaceExW() Function

GetDiskFreeSpaceExW() has several parameters:

  • An in-parameter specifying the drive's path
  • Three out-parameters capturing the available free bytes, total bytes (drive size), and total free bytes

Implementing the Solution

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))
    }
}
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template