通过C++获取微型SD卡的大小

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

本文关键字:SD C++ 获取 微型 通过      更新时间:2023-10-16

我正在寻找一些函数,该函数将返回挂载到/dev/sdb的micro SD卡的总容量。我不太关心可用空间,我关心驱动器的总容量。我需要一个可靠和准确的功能。如果不存在,我将如何创建一个?

谢谢!

blockdev的strace告诉我你可以使用:

#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
}

(将 SDX 替换为设备节点名称(

注意 如果您的编译器已经支持uint64_t,则更喜欢使用它(包括<cstdint>(

您可以在/sys/目录中读取一个特殊文件:

/sys/block/sdb/sdb1/size

它返回以字节为单位的大小。