Home > Backend Development > Golang > How to Access All Windows Drives Programmatically in Go?

How to Access All Windows Drives Programmatically in Go?

DDD
Release: 2024-10-29 02:48:30
Original
758 people have browsed it

How to Access All Windows Drives Programmatically in Go?

Accessing All Windows Drives in Go

In Go, retrieving a comprehensive listing of all drives on a Windows system requires a specific approach. To avoid manual specification of drive letters like "program.exe C:" for each drive, a dynamic solution is sought.

By utilizing the GetLogicalDrives function from the kernel32.dll, it's possible to obtain a bit map representing available drives. The bitsToDrives function converts this bit map into a list of corresponding drive letters, such as ["A", "B", "C",...].

The following Go code demonstrates this approach:

<code class="go">package main

import (
    "fmt"
    "syscall"
)

func main() {

    kernel32, _ := syscall.LoadLibrary("kernel32.dll")
    getLogicalDrivesHandle, _ := syscall.GetProcAddress(kernel32, "GetLogicalDrives")

    var drives []string

    if ret, _, callErr := syscall.Syscall(uintptr(getLogicalDrivesHandle), 0, 0, 0, 0); callErr != 0 {
        // handle error
    } else {
        drives = bitsToDrives(uint32(ret))
    }

    fmt.Printf("%v", drives)

}

func bitsToDrives(bitMap uint32) (drives []string) {
    availableDrives := []string{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"}

    for i := range availableDrives {
        if bitMap&1 == 1 {
            drives = append(drives, availableDrives[i])
        }
        bitMap >>= 1
    }

    return
}</code>
Copy after login

Using this method, you can now iterate through all drives on a Windows system seamlessly, without relying on user-specified drive letters.

The above is the detailed content of How to Access All Windows Drives Programmatically in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template