This code identifies and monitors removable drives connected to a...

September 2, 2025 at 04:17 AM

#include <windows.h> #include <fileapi.h> #include <iostream> #include <fstream> #include <string> #include <vector> #include <algorithm> const std::string INC_FILE = "Storage Edits\\drive.inc"; // Helper: get all removable drives std::vector<std::pair<std::string, std::string>> GetRemovableDrives() { std::vector<std::pair<std::string, std::string>> drives; DWORD mask = GetLogicalDrives(); for (char letter = 'A'; letter <= 'Z'; ++letter) { if (mask & 1) { std::string root = std::string(1, letter) + ":\\"; UINT type = GetDriveTypeA(root.c_str()); if (type == DRIVE_REMOVABLE) { char volName[MAX_PATH] = {0}; if (GetVolumeInformationA(root.c_str(), volName, MAX_PATH, nullptr, nullptr, nullptr, nullptr, 0)) { std::string name = volName[0] ? volName : "USBDrive"; std::replace(name.begin(), name.end(), ' ', '_'); // replace spaces drives.push_back({name, std::string(1, letter) + ":"}); } } } mask >>= 1; } return drives; } // Write INC file void WriteDriveINC(const std::vector<std::pair<std::string, std::string>>& drives) { std::ofstream file(INC_FILE, std::ios::trunc); file << "[Variables]\n"; for (auto& [name, letter] : drives) { file << name << "=" << letter << "\n"; } file.close(); } // Window procedure for device change events LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { if (msg == WM_DEVICECHANGE) { if (wParam == DBT_DEVICEARRIVAL || wParam == DBT_DEVICEREMOVECOMPLETE) { auto drives = GetRemovableDrives(); WriteDriveINC(drives); } } return DefWindowProc(hwnd, msg, wParam, lParam); } int main() { // Ensure folder exists CreateDirectoryA("Storage Edits", NULL); // Initial write WriteDriveINC(GetRemovableDrives()); // Create a hidden window to receive device notifications WNDCLASSA wc = {}; wc.lpfnWndProc = WndProc; wc.lpszClassName = "DriveListenerWindow"; RegisterClassA(&wc); HWND hwnd = CreateWindowA("DriveListenerWindow", "DriveListener", 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL); MSG msg; while (GetMessageA(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessageA(&msg); } return 0; }

This code identifies and monitors removable drives connected to a Windows system and writes their information into a configuration .inc file. Here's a breakdown of what it does:


1. Header Files

It includes various headers for Windows API and standard utilities:

  • windows.h, fileapi.h: For interacting with Windows functionality like drive information and handling messages.
  • iostream, fstream, etc.: For input/output and string manipulation.

2. Constants

Defines INC_FILE as the path and name for the output configuration file where removable drive data will be stored: Storage Edits\drive.inc.


3. GetRemovableDrives Function

  • This function detects all removable drives currently connected to the system.
  • It uses the GetLogicalDrives function to get a bitmask of available drives (A: to Z:), checks whether each one is removable using GetDriveTypeA, and retrieves its volume label using GetVolumeInformationA.
  • Any spaces in the volume name are replaced with underscores.
  • The result is a list (std::vector) of pairs containing the volume name and drive letter (e.g., {"MyUSBDrive", "E:"}).

4. WriteDriveINC Function

  • Writes the list of removable drives to the drive.inc file.
  • The format of the file is:
    [Variables]
    DriveName1=DriveLetter1
    DriveName2=DriveLetter2
    
  • Any previous contents of the file are replaced (std::ios::trunc mode).

5. WndProc Function

  • This is a callback function (window procedure) used to handle Windows system messages.
  • It monitors device changes using the WM_DEVICECHANGE message. Specifically:
    • When a device is added (DBT_DEVICEARRIVAL) or removed (DBT_DEVICEREMOVECOMPLETE), the program updates the drive.inc file by calling GetRemovableDrives and writing the new list of drives using WriteDriveINC.

6. main Function

The main function does the following:

  1. Ensures the output folder (Storage Edits) exists by calling CreateDirectoryA.
  2. Writes the initial list of removable drives to the drive.inc file using WriteDriveINC.
  3. Creates a hidden window to receive system messages, specifically those for detecting device changes:
    • A custom window class is registered using RegisterClassA, and a window is created with CreateWindowA. The window does not display anything on the screen but allows the program to receive system device notifications.
  4. Runs an infinite message-processing loop (GetMessageA) to handle Windows events, ensuring the program updates the drive.inc file when changes (like USB drive insertion/removal) occur.

Purpose

This program continuously monitors removable (e.g., USB) drives. It creates or updates a configuration file (drive.inc) that lists all currently connected removable drives with their names and letters.

The following actions occur:

  • On startup: Writes the initial list of removable drives to drive.inc.
  • When USB devices are plugged or unplugged: Detects the change, updates the drive list, and rewrites drive.inc.

Key Features

  1. Dynamic Drive Monitoring: Automatically detects when drives are added or removed.
  2. Outputs Configuration File: Runnable in systems where a consumable .inc file with settings (e.g., drive names and letters) is needed.
  3. Hidden Execution: The program runs silently, interacting with the system without additional user interface.

Use Case

This code could be useful in scenarios where a program or system component requires real-time information about connected USB drives, such as:

  • Synchronizing files to/from specific drives.
  • Logging drive usage.
  • Using removable drives for device authentication or configuration.

Example drive.inc Output

After detecting a USB drive named "MY_USB" assigned to drive "E:", the drive.inc file may look like this:

[Variables]
MY_USB=E:

If another drive is plugged in, such as "AnotherDrive" at "F:", it is updated to:

[Variables]
MY_USB=E:
AnotherDrive=F:
Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node