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

4

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?

Kersey answered 30/8, 2011 at 13:31 Comment(3)
Yep..I have checked but I couldnt found any resourcesKersey
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".Yukikoyukio
listing the harddisks either attached or mounted is enough.Kersey
A
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;
}
Armistice answered 30/8, 2011 at 14:37 Comment(1)
It only works if the partitions are mountedDelibes
A
8

You can use libparted

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

ped_device_probe_all() is the call to detect the devices.

Autoicous answered 30/8, 2011 at 13:38 Comment(1)
No worries mate. If it does what you want remember to mark it as the answer :)Autoicous
R
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

Rejoice answered 30/8, 2011 at 13:43 Comment(0)
O
0

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

system("fdisk -l");
Overstudy answered 30/8, 2011 at 13:39 Comment(3)
How does fdisk does it then? What language do you think fdisk is written in?Sheryllshetland
@Sheryllshetland 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... FWIWRejoice
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.Transceiver

© 2022 - 2024 — McMap. All rights reserved.