Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to list the harddisks attached to a Linux machine using C++?

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?

like image 473
balu Avatar asked Aug 30 '11 13:08

balu


People also ask

How do I get a list of hard drives in Linux?

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.

How do you check how many hard disks I have in Linux?

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

Where are hard drives located in Linux?

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.


1 Answers

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;
}
like image 61
André Puel Avatar answered Oct 03 '22 01:10

André Puel