CreateFile() failed with error code 32 while reading pendrive

Viewed 2465

I am trying to read raw bytes from a pen drive 'E:', but it gives error code 32 when trying to open the drive using CreateFIle(). My code is as follows:

wchar_t  wszDrive[7];
wszDrive[0] = '\\';
wszDrive[1] = '\\';
wszDrive[2] = '.';
wszDrive[3] = '\\';
wszDrive[4] = 'e';
wszDrive[5] = ':';
wszDrive[6] = '\0';

hDevice = CreateFile(wszDrive,  //drive name to open                        

        GENERIC_READ | GENERIC_WRITE,   ////must be opened with exclusive access(No Sharing)
        0,                              // no access to the drive
        NULL,             // default security attributes
        OPEN_EXISTING,    // disposition i.e. if file already exist
        0,                // file attributes
        NULL);            // do not copy file attributes

if (hDevice == INVALID_HANDLE_VALUE) // cannot open the drive
{
    printf("CreateFile() failed! from read with error %d.\n", GetLastError());// Program prints this line. with error code 32.
    return (FALSE);
}
else
    cout << "\nCreateFile() successful! in read";

Edit: The CreateFile() runs fine without errors if I use FILE_SHARE_READ | FILE_SHARE_WRITE:

hDevice = CreateFile(wszDrive,                                            
                        GENERIC_READ | 
                        GENERIC_WRITE,
                        FILE_SHARE_READ | FILE_SHARE_WRITE,
                        NULL,             
                        OPEN_EXISTING,    
                        0,                
                        NULL);

Why cannot I run with exclusive access?

1 Answers

Error 32 is ERROR_SHARING_VIOLATION.

The process cannot access the file because it is being used by another process.

It means there is already an open handle to the drive, and that handle is using access/sharing rights which are not compatible with the access/sharing rights you are requesting.

That is why you can't open the drive for exclusive access, but you can open it for read/write sharing - the drive is already open elsewhere for reading/writing.

If you want to know where exactly, you can use a tool like SysInternals Process Explorer to see which processes have open handles to which files/folders, devices, etc.

Related