• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: How to detect block devices on Linux?

Resolved: How to detect block devices on Linux?

0
By Isaac Tonny on 16/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

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; } } [/code]

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".

Answer:

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; } } [/code]

If you have better answer, please add a comment about this, thank you!

block-device c++ linux
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: How to efficient create SimpleITK image?

01/04/2023

Resolved: How can I write CSS selector(s) that apply to table rows for all td elements on that row after a td with a certain class?

01/04/2023

Resolved: How do I use SetWindowText with Unicode in Win32 using PowerShell?

01/04/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.