Skip to content

Instantly share code, notes, and snippets.

@JubbaSmail
Created November 13, 2014 09:37
Show Gist options
  • Save JubbaSmail/6b7e703a7cbf5ecf33ae to your computer and use it in GitHub Desktop.
Save JubbaSmail/6b7e703a7cbf5ecf33ae to your computer and use it in GitHub Desktop.
#include <windows.h>
#if define UNICODE
#define CreateFile CreateFileW
#define GetDriveType GetDriveTypeW
#define GetLogicalDriveStrings GetLogicalDriveStringsW
#else
#define CreateFile CreateFileA
#define GetDriveType GetDriveTypeA
#define GetLogicalDriveStrings GetLogicalDriveStringsA
#endif
BOOL ejectDisk(char driveLetter[])
{
char tmp[10] = "\\\\.\\";
HANDLE handle = CreateFile(strcat(tmp, driveLetter), GENERIC_READ, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
DWORD bytes = 0;
//DeviceIoControl(handle, FSCTL_LOCK_VOLUME, 0, 0, 0, 0, &bytes, 0);
//DeviceIoControl(handle, FSCTL_DISMOUNT_VOLUME, 0, 0, 0, 0, &bytes, 0);
DeviceIoControl(handle, IOCTL_STORAGE_EJECT_MEDIA, 0, 0, 0, 0, &bytes, 0);
CloseHandle(handle);
return TRUE;
}
char *substr(const char *inpStr, char *outStr, size_t startPos, size_t strLen) {
strncpy(outStr, inpStr + startPos, strLen);
outStr[strLen] = '\0';
return outStr;
}
void EjectCDROMs()
{
DWORD dwSize = MAX_PATH;
char szLogicalDrives[MAX_PATH] = { 0 };
DWORD dwResult = GetLogicalDriveStrings(dwSize, szLogicalDrives); //szLogicalDrives = C:<null>D:<null>F:<null><null>
if (dwResult > 0)
{
char* szSingleDrive = szLogicalDrives;//Split szLogicalDrives by <null>
while (*szSingleDrive)
{
CHAR drive[3];
substr(szSingleDrive, drive, 0, 2);
if (GetDriveType(drive) == DRIVE_CDROM)//DRIVE_REMOVABLE ==> USB //DRIVE_FIXED ==> C: D: //DRIVE_CDROM ==> CDROM
ejectDisk(drive);
// get the next drive
szSingleDrive += strlen(szSingleDrive) + 1;
}
}
}
int main(int argc, LPTSTR argv[])
{
EjectCDROMs();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment