Getting the size of a micro SD card via C++

我的梦境 提交于 2019-12-24 10:59:05

问题


I am looking for some function that will return the total capacity of a micro SD card mounted to /dev/sdb. I do not care so much about free space I care about total capacity of the drive. I need a reliable and accurate function. If there is none in existence how would I go about creating one?

Thanks!


回答1:


strace for blockdev tells me you could 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 by device node name)

Note prefer using uint64_t if your compiler supports it already (include <cstdint>)




回答2:


You can just read a special file in the /sys/ directory:

/sys/block/sdb/sdb1/size

It returns the size in bytes.



来源:https://stackoverflow.com/questions/7829300/getting-the-size-of-a-micro-sd-card-via-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!