gpt4 book ai didi

c - Linux C 编程 : How to get a device's partition infomation?

转载 作者:IT王子 更新时间:2023-10-29 00:42:58 25 4
gpt4 key购买 nike

我是 Linux c 编程的新手,是否有任何 API 可以获取设备的分区信息?

最佳答案

Akash Rawal 的回答非常接近。一个好方法是使用 libblkid。

这是获取分区 uuid 的示例:Using libblkid to find UUID of a partition .

我结合了上面显示的代码和 libblkid 引用菜单中的示例并生成了以下工作程序:

#include <stdio.h>
#include <string.h>
#include <err.h>
#include <blkid/blkid.h>


int main (int argc, char *argv[]) {
blkid_probe pr = blkid_new_probe_from_filename(argv[1]);
if (!pr) {
err(1, "Failed to open %s", argv[1]);
}

// Get number of partitions
blkid_partlist ls;
int nparts, i;

ls = blkid_probe_get_partitions(pr);
nparts = blkid_partlist_numof_partitions(ls);
printf("Number of partitions:%d\n", nparts);

if (nparts <= 0){
printf("Please enter correct device name! e.g. \"/dev/sdc\"\n");
return;
}

// Get UUID, label and type
const char *uuid;
const char *label;
const char *type;

for (i = 0; i < nparts; i++) {
char dev_name[20];

sprintf(dev_name, "%s%d", argv[1], (i+1));

pr = blkid_new_probe_from_filename(dev_name);
blkid_do_probe(pr);

blkid_probe_lookup_value(pr, "UUID", &uuid, NULL);

blkid_probe_lookup_value(pr, "LABEL", &label, NULL);

blkid_probe_lookup_value(pr, "TYPE", &type, NULL);

printf("Name=%s, UUID=%s, LABEL=%s, TYPE=%s\n", dev_name, uuid, label, type);

}

blkid_free_probe(pr);

return 0;
}

用法:

gcc -o getuuid getuuid.c -lblkid
sudo ./getuuid /dev/sdc
Number of partitions:1
Name=/dev/sdc1, UUID=754A-CE25, LABEL=KINGSTON, TYPE=vfat

关于c - Linux C 编程 : How to get a device's partition infomation?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8663643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com