c++linuxblock-device

How to detect block devices on Linux?


With C++ on Linux, how does one detect block devices? Right now, I'm using this code:

for (const auto &entry : std::filesystem::directory_iterator("/dev/"))
{
    std::string name = entry.path().filename().string();
    if (name.find("sd") == 0 || name.find("nvme") == 0 || name.find("hd") == 0 || name.find("vd") == 0 || name.find("xvd") == 0)
    {
        std::cout << "Found device: " << entry.path() << std::endl;
    }
}

Which works well enough in practice, but almost certainly isn't the way it's "supposed to be done". And it isn't perfect either, as it misses losetup devices because I didn't include "loop", it also misses Network Block Devices because I didn't include "nbd".


Solution

  • std::filesystem::directory_entry has an is_block_file() method for this exact purpose:

    Checks whether the pointed-to object is a block device.

    For example:

    for (const auto &entry : std::filesystem::directory_iterator("/dev/"))
    {
        if (entry.is_block_file())
        {
            std::cout << "Found device: " << entry.path() << std::endl;
        }
    }