Search code examples
c++winapilow-level

"Access is Denied" CreateFile() on Usb stick


My goal is to read all bytes of an USB stick.

I tryed to open "D:" with CreateFile() and fopen() but an ERROR is raised :

"Access is Denied"

HANDLE disk = CreateFile("D:", 
                         GENERIC_READ,
                         FILE_SHARE_READ,        
                         NULL,
                         OPEN_EXISTING,
                         FILE_ATTRIBUTE_NORMAL,
                         NULL);

    if (disk == INVALID_HANDLE_VALUE) {
        printf ("%d\n", GetLastError());
        return -1;
    }

This code prints 5 (="Access is Denied").

I'm using Windows 8 and C++.

Can someone explain to me why an error is raised ?


Solution

  • Your file path is invalid.

    To open the device with the letter D, you should use the following path:

    "\\.\D:"

    This is explained in the docs