写一段Linux下判断是否有USB设备连接的代码
时间: 2023-04-10 11:01:55 浏览: 83
以下是一段Linux下判断是否有USB设备连接的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
int main() {
DIR *dir;
struct dirent *entry;
char path[PATH_MAX];
dir = opendir("/sys/bus/usb/devices/");
if (dir == NULL) {
perror("opendir");
exit(EXIT_FAILURE);
}
while ((entry = readdir(dir)) != NULL) {
if (entry->d_type == DT_LNK && strstr(entry->d_name, "usb")) {
snprintf(path, PATH_MAX, "/sys/bus/usb/devices/%s/driver", entry->d_name);
if (access(path, F_OK) == -1) {
printf("USB device %s is not connected.\n", entry->d_name);
} else {
printf("USB device %s is connected.\n", entry->d_name);
}
}
}
closedir(dir);
return 0;
}
```
这段代码通过读取/sys/bus/usb/devices/目录下的设备信息来判断是否有USB设备连接。具体来说,它遍历该目录下的所有文件,如果文件名中包含"usb"字符串,则认为这是一个USB设备。然后它会检查该设备的驱动程序是否存在,如果不存在,则认为该设备未连接,否则认为该设备已连接。