Linux C语言/C++获取所有硬盘分区的卷标、UUID和文件系统类型
Linux C语言获取所有硬盘分区的卷标、UUID和文件系统类型
一些网上已有的方法只能探测挂在后的文件系统。那么我们先不要挂载怎么做呢?
安装 blkid 库
sudo apt install libblkid1 libblkid-dev # 大部分发行版应该有预装
参考 blkid 代码
apt source blkid libblkid1 # 不用 sudo
经过编译调试,可以大概知道代码逻辑。草稿代码:
#include <blkid/blkid.h>
#include <stdio.h>
void print_tag(blkid_dev device) {
const char* devname = blkid_dev_devname(device);
printf("\e[1m%s:\e[0m\n", devname);
blkid_tag_iterate iter = blkid_tag_iterate_begin(device);
const char * type, *value;
while (blkid_tag_next(iter, &type, &value) == 0) {
printf("%s: %s\n", type, value);
}
blkid_tag_iterate_end(iter);
}
// 查看某个分区,如 /dev/sda1
int single_block(const char* device_path) {
blkid_cache cache = nullptr;
if (blkid_get_cache(&cache, nullptr) < 0) return 1;
blkid_dev dev = blkid_get_dev(cache, device_path, BLKID_DEV_NORMAL);
if (!dev) return 1;
print_tag(dev);
blkid_put_cache(cache);
return 0;
}
// 查看全部分区
int all_block() {
blkid_cache cache = nullptr;
if (blkid_get_cache(&cache, nullptr) < 0) { return 1; }
blkid_dev_iterate iter;
blkid_dev dev;
blkid_probe_all(cache);
iter = blkid_dev_iterate_begin(cache);
blkid_dev_set_search(iter, nullptr, nullptr);
while (blkid_dev_next(iter, &dev) == 0) {
dev = blkid_verify(cache, dev);
if (!dev) continue;
print_tag(dev);
printf("\n");
}
blkid_dev_iterate_end(iter);
blkid_put_cache(cache);
return 0;
}
int main(int argc, const char* argv[]) {
if (argc == 1)
all_block();
else {
for (int order = 1; order < argc; order++) {
single_block(argv[order]);
printf("\n");
}
}
}
编译命令链接 libblkid.so.1
g++ main.cpp -o main -lblkid
执行效果,无需 sudo,无需挂载:
$ ./main /dev/nvme0n1p10
/dev/nvme0n1p10:
LABEL: WinRE_DRV
BLOCK_SIZE: 512
UUID: F16DD05C749E****
TYPE: ntfs
PARTUUID: 801266cd-552d-40d5-****-cecf865e1558
输出类似 blkid,有需要的自己修改即可获取到需要的信息。