P
P
President422014-11-12 21:42:24
go
President42, 2014-11-12 21:42:24

How to work with usb media in Golang?

In general, I need a function that returns an array with the addresses of all flash drives connected to the computer (like, "E:\\") - how to do this in Go? First of all, the decision for Windows interests.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaly Yakovenko, 2015-04-11
@Xazzzi

Flash drives are not flash drives, but the case was dealt with logical drives on StackOverflow, 2 solutions were proposed:
1) Simple - try to get a file descriptor for the root directory of logical drives with each letter from A to Z:

func getdrives() (r []string){
    for _, drive := range "ABCDEFGHIJKLMNOPQRSTUVWXYZ"{
        _, err := os.Open(string(drive)+":\\")
        if err == nil {
            r = append(r, string(drive))
        }
    }
    return
}

2) The correct, but OS-dependent option (however, the first one is also OS-dependent): call the WinApi getLogicalDrives function, which returns the bitmask of available logical drives:
//переводит битмаску в буквы
func bitsToDrives(bitMap uint32) (drives []string) {
    availableDrives := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    for i := 0; i < 32; i++ {
        if bitMap&1 == 1 {
            drives = append(drives, availableDrives[bitMap&1])
        }
        bitMap >>= 1
    }
    return
}

func main() {
    kernel32, _ = syscall.LoadLibrary("kernel32.dll")
    getLogicalDrivesHandle, _ = syscall.GetProcAddress(kernel32, "GetLogicalDrives")
    if ret, _, callErr := syscall.Syscall(uintptr(getLogicalDrivesHandle), 0, 0, 0, 0); callErr != 0 {
        // handle error
    } else {
        bitsToDrives(uint32(ret))
    }
}

Source.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question