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?

3
  • 1
    Yep..I have checked but I couldnt found any resources
    – balu
    Aug 30, 2011 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". Aug 30, 2011 at 13:49
  • 1
    listing the harddisks either attached or mounted is enough.
    – balu
    Aug 30, 2011 at 13:51

4 Answers 4

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;
}
1
  • It only works if the partitions are mounted
    – Sunlight
    10 hours ago
8

You can use libparted

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

ped_device_probe_all() is the call to detect the devices.

1
  • No worries mate. If it does what you want remember to mark it as the answer :) Aug 30, 2011 at 13:54
6

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

0

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

system("fdisk -l");
3
  • 2
    How does fdisk does it then? What language do you think fdisk is written in? Aug 30, 2011 at 13:41
  • 2
    @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, 2011 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, 2018 at 21:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.