Getting micro SD card size via C ++

I am looking for some function that will return the total capacity of a micro SD card installed on / dev / sdb. I don’t care about the free space, I care about the full capacity of the drive. I need a reliable and accurate function. If it does not exist, how can I create it?

Thank!

+1
source share
2 answers

strace for blockdevtells me you can use:

#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <sys/ioctl.h>
#include <linux/fs.h>

int main()
{
    unsigned long long size;
    int fd = open("/dev/sdx", O_RDONLY);
    ioctl(fd, BLKGETSIZE64, &size);

    std::cout << size << std::endl;
    std::cout << (size>>20) << std::endl; // MiBytes
}

(replace sdx with the node name device)

Note prefers to use uint64_tif your compiler already supports it (include <cstdint>)

+4
source

/sys/:

/sys/block/sdb/sdb1/size

.

+1

Source: https://habr.com/ru/post/1547298/


All Articles