Home >Backend Development >Golang >How do I list all available drives in Windows using Go?

How do I list all available drives in Windows using Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-29 21:15:30443browse

How do I list all available drives in Windows using Go?

How to List All Drives on Windows Using Go

Programs often require the ability to interact with different drives on a system, such as searching for a particular file type. While it's possible to specify the drive letter manually, it's more convenient and efficient to list all drives automatically. In Go, this can be achieved by leveraging the GetLogicalDrives function.

Getting the List of Drives

The GetLogicalDrives function returns a bit map representing all the available drives. Each bit corresponds to a drive letter.

<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>

The bitsToDrives() function converts the bit map to a string array of drive letters.

Iterating Through the Drives

Once the list of drives has been obtained, you can iterate through them to perform any desired actions, such as searching for files.

By following these steps using Go, you can efficiently get a listing of all drives on Windows and perform operations on them as needed.

The above is the detailed content of How do I list all available drives in Windows using Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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