I need to list the harddisk drives attached to the Linux machine using the C++.
Is there any C or C++ function available to do this?
The easiest way to list disks on Linux is to use the “lsblk” command with no options. The “type” column will mention the “disk” as well as optional partitions and LVM available on it.
sudo fdisk -l will list your disks and a bunch of stats about them, including the partitions. The disks are generally in the form of /dev/sdx and partitions /dev/sdxn , where x is a letter and n is a number (so sda is the first physical disk and sda1 is the first partition on that disk).
Find Hard Disk Drive Details In Linux Using /proc Each device details are stored in a separate directory under /proc directory. The storage devices' details will be available in "/proc/scsi/scsi" file.
Take a look at this simple /proc/mounts parser I made.
#include <fstream>
#include <iostream>
struct Mount {
std::string device;
std::string destination;
std::string fstype;
std::string options;
int dump;
int pass;
};
std::ostream& operator<<(std::ostream& stream, const Mount& mount) {
return stream << mount.fstype <<" device \""<<mount.device<<"\", mounted on \""<<mount.destination<<"\". Options: "<<mount.options<<". Dump:"<<mount.dump<<" Pass:"<<mount.pass;
}
int main() {
std::ifstream mountInfo("/proc/mounts");
while( !mountInfo.eof() ) {
Mount each;
mountInfo >> each.device >> each.destination >> each.fstype >> each.options >> each.dump >> each.pass;
if( each.device != "" )
std::cout << each << std::endl;
}
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With