Home >Backend Development >Golang >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&1 == 1 { drives = append(drives, availableDrives[i]) } bitMap >>= 1 } return }</code>
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!