Home > Backend Development > Golang > How to Get a Listing of All Drives on a Windows System Using Go?

How to Get a Listing of All Drives on a Windows System Using Go?

Barbara Streisand
Release: 2024-10-28 19:43:02
Original
314 people have browsed it

How to Get a Listing of All Drives on a Windows System Using Go?

Getting Drive Listing on Windows Using Go

To automatically search for files on all drives on a Windows system, it's necessary to retrieve a listing of all drives using Go. The Go programming language provides functions for interacting with the Windows API, allowing for enumeration of logical drives.

Solution

The solution involves calling the GetLogicalDrives function from the kernel32.dll library. This function returns a bit map indicating the available drives. By processing this bit map, we can obtain the drive letters corresponding to the available drives:

<code class="go">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&amp;1 == 1 {
            drives = append(drives, availableDrives[i])
        }
        bitMap >>= 1
    }

    return
}</code>
Copy after login

The bitsToDrives function converts the bit map into an array of drive letters, and the main function calls fmt.Printf() to print the list of drives. This code allows you to dynamically search for files on all available drives without requiring user input for drive letters.

The above is the detailed content of How to Get a Listing of All Drives on a Windows System Using 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template