SysTools Logo SysTools


C, WinAPI: Find CD/DVD disk drive


/*
  Find CD/DVD disk drive.
  Binary safe, Unicode aware.

  input:
    filename - filename to check

  return:
    '\0' - on error (drive not found)
    'A'..'Z' - drive letter

  example of usage:
    DriveChar = FindDiskDrive(TEXT("Folder1\\Folder2\\FileName.ext"));
*/

TCHAR FindDiskDrive(TCHAR *filename) {
TCHAR path[MAX_PATH], result;
DWORD pem, drv;
  // by default - drive not found
  result = 0;
  // sanity check
  if (filename && *filename) {
    // surpass system Retry/Abort/Ignore dialog
    // for GetFileAttributes() on not ready drives
    pem = SetErrorMode(SEM_FAILCRITICALERRORS);
    // drive path
    // note that using lstrcpy() with lstrcat()
    // instead adds another function to the import
    // and static data with this string
    // not to mention lstrcat() is not binary safe
    // so you can't handle MAX_PATH overflow
    path[0] = TEXT('A');
    path[1] = TEXT(':');
    path[2] = TEXT('\\');
    // add file path
    lstrcpyn(&path[3], filename, MAX_PATH - 3);
    // for each of logical drives
    drv = GetLogicalDrives();
    while (drv) {
      // drive exists
      if (drv & 1) {
        // cut path to drive
        path[3] = 0;
        // drop bit of drive if not a CD/DVD-ROM
        drv ^= (GetDriveType(path) == DRIVE_CDROM) ? 0 : 1;
        // restore full path for GetFileAttributes()
        path[3] = filename[0];
        // drive is a CD/DVD-ROM and file exists
        if ((drv & 1) && (GetFileAttributes(path) != INVALID_FILE_ATTRIBUTES)) {
          result = path[0];
          break;
        }
      }
      // next drive
      path[0]++;
      drv >>= 1;
    }
    // restore system defaults
    SetErrorMode(pem);
  }
  return(result);
}

2015.09.04


[ Код ]