5

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?

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
balu
  • 55
  • 2
  • 3
  • 1
    Yep..I have checked but I couldnt found any resources – balu Aug 30 '11 at 13:42
  • 1
    Just a disambiguation, do you want to list the harddisks attached or mounted? Linux has a very nice interface with the system using the filesystem. Please take a look at the dir "/dev/disk". – André Puel Aug 30 '11 at 13:49
  • 1
    listing the harddisks either attached or mounted is enough. – balu Aug 30 '11 at 13:51

4 Answers4

9

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;
}
André Puel
  • 8,741
  • 9
  • 52
  • 83
7

You can use libparted

http://www.gnu.org/software/parted/api/

ped_device_probe_all() is the call to detect the devices.

Peter Short
  • 762
  • 6
  • 17
5

Its not a function, but you can read the active kernel partitions from /proc/partitions or list all the block devices from dir listing of /sys/block

tMC
  • 18,105
  • 14
  • 62
  • 98
0

Nope. No standard C or C++ function to do that. You will need a API. But you can use:

system("fdisk -l");
André Puel
  • 8,741
  • 9
  • 52
  • 83
yatagarasu
  • 550
  • 6
  • 13
  • 2
    How does fdisk does it then? What language do you think fdisk is written in? – static_rtti Aug 30 '11 at 13:41
  • 1
    @static_rtti running strace on fdisk. It looks like it opens /proc/partitions to get a device listing, than opens each device file RO and tries to read a partition table from each device... FWIW – tMC Aug 30 '11 at 13:56
  • Nope, Don't parse fdisk output, or any command at all. It may be translated to the user's locale or have a non-stable output. – Salamandar Jul 15 '18 at 21:18