Skip to content

Instantly share code, notes, and snippets.

@gynvael
Created February 3, 2021 21:27
Show Gist options
  • Save gynvael/ed67e621d5f14f18a323c4d078d7d743 to your computer and use it in GitHub Desktop.
Save gynvael/ed67e621d5f14f18a323c4d078d7d743 to your computer and use it in GitHub Desktop.
Check if device path exists on Windows
#include <Windows.h>
#include <stdio.h>
#include <string>
using std::string;
void testdev(string devname) {
string path = "\\\\?\\Global\\GLOBALROOT\\Device\\" + devname;
printf("----------------- %s\n", devname.c_str());
HANDLE h = CreateFile(
path.c_str(),
GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
DWORD error = GetLastError();
printf("Handle: %p, Error: %u\n", h, (unsigned)error);
if (h != INVALID_HANDLE_VALUE ||
(h == INVALID_HANDLE_VALUE && error == 5)) {
puts("Found the device!");
} else {
puts("Device not present");
}
if (h != INVALID_HANDLE_VALUE) {
CloseHandle(h);
}
}
int main(void) {
testdev("Beep"); // Everyone should have access.
testdev("PartmgrControl"); // Only admin has access.
testdev("IDontExist"); // Guess.
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment