Home > Backend Development > Golang > How Can I Efficiently Get a List of Available Drives in Windows Using Golang?

How Can I Efficiently Get a List of Available Drives in Windows Using Golang?

DDD
Release: 2024-10-30 09:36:02
Original
388 people have browsed it

How Can I Efficiently Get a List of Available Drives in Windows Using Golang?

Getting a List of Drives on Windows Using Golang

Seeking a more efficient way to search across all drives on a Windows system for a specific file type, Go programmers may wonder if it's possible to automatically obtain a list of available drives without user-specified input.

Solution using GetLogicalDrives and Bit Manipulation:

To list the drives on a Windows system, one can leverage the GetLogicalDrives function. This function returns a bit mask with each bit representing the availability of a drive letter from 'A' to 'Z.'

Here's a Golang code snippet that demonstrates the process:

<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

In this code, the GetLogicalDrives function is called to obtain the bit mask. The bitmask is then processed using bit manipulation techniques to extract the available drive letters and store them in the drives slice. By iterating through this slice, you can easily access and process all available drives on the system.

The above is the detailed content of How Can I Efficiently Get a List of Available Drives in Windows Using Golang?. 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