如何判断GVolume实例所属设备类型(硬盘/光驱/软盘/USB)?
判断GVolume的设备类型
要判断GVolume对应的设备类型,你需要通过GVolume关联的GDrive实例来获取设备属性,具体步骤如下:
首先从GVolume获取对应的GDrive:
GDrive *drive = g_volume_get_drive(volume); if (drive == NULL) { // 处理无关联驱动器的情况(比如网络卷) g_object_unref(drive); return; }通过GDrive核心方法区分基础类型:
- 区分可移除/固定设备:
使用g_drive_is_removable(drive)判断是否为可移除设备——USB、软盘、CD-ROM通常返回TRUE,内置硬盘返回FALSE。 - 区分媒体可移除设备:
使用g_drive_is_media_removable(drive)判断是否支持媒体弹出——CD-ROM、软盘返回TRUE,USB硬盘/内置硬盘返回FALSE。
- 区分可移除/固定设备:
通过图标名称精准判断设备类型:
GDrive的图标名称通常对应设备类型,可通过g_icon_to_string()获取:GIcon *icon = g_drive_get_icon(drive); gchar *icon_name = g_icon_to_string(icon); if (g_str_has_prefix(icon_name, "drive-harddisk")) { // 硬盘设备 } else if (g_str_has_prefix(icon_name, "drive-optical")) { // CD-ROM/DVD设备 } else if (g_str_has_prefix(icon_name, "drive-floppy")) { // 软盘设备 } else if (g_str_has_prefix(icon_name, "drive-usb")) { // USB设备 } g_free(icon_name); g_object_unref(icon);借助UDEV属性获取底层总线信息(更准确):
如果程序依赖libudev,可通过GDrive获取对应UDEV设备,读取ID_BUS属性:// 需要链接GUDev库 GUdevDevice *udev_device = g_drive_get_device(drive); const gchar *bus_type = g_udev_device_get_property(udev_device, "ID_BUS"); if (g_str_equal(bus_type, "ata") || g_str_equal(bus_type, "scsi")) { // 内置硬盘 } else if (g_str_equal(bus_type, "usb")) { // USB设备 } else if (g_str_equal(bus_type, "floppy")) { // 软盘设备 } else if (g_str_equal(bus_type, "cdrom")) { // CD-ROM设备 } g_object_unref(udev_device);
注意:使用完GDrive、GIcon等对象后,记得调用g_object_unref()释放资源,避免内存泄漏。
内容的提问来源于stack exchange,提问作者Igor
相关产品推荐
相关产品推荐

