并根据解析出来的信息,获取设备的pid和vid,请用C语言写出程序
时间: 2024-02-29 22:51:07 浏览: 26
根据解析出来的信息,可以找到包含设备pid和vid信息的一行:
```
PRODUCT: 1224/2a25/100
```
我们可以通过字符串处理函数和 sscanf 函数提取出 pid 和 vid:
```c
#include <stdio.h>
#include <string.h>
#include <regex.h>
#define MAX_MATCHES 10
int main() {
char buffer[] = "ACTION=remove DEVPATH=/devices/pci0000:00/0000:00:08.1/0000:09:00.3/usb3/3-3/3-3.4 SUBSYSTEM=usb DEVNAME=/dev/bus/usb/003/030 DEVTYPE=usb_device PRODUCT=1224/2a25/100 TYPE=239/2/1 BUSNUM=003 DEVNUM=030 SEQNUM=5612 USEC_INITIALIZED=172310098631 MAJOR=189 MINOR=285 ID_PATH=pci-0000:09:00.3-usb-0:3.4 ID_PATH_TAG=pci-0000_09_00_3-usb-0_3_4";
regex_t regex;
regmatch_t matches[MAX_MATCHES];
// compile the regular expression
if (regcomp(®ex, "[A-Z_]+=[^ ]+", REG_EXTENDED) != 0) {
printf("Failed to compile regex\n");
return 1;
}
// match the regular expression against the buffer
int offset = 0;
while (regexec(®ex, buffer + offset, MAX_MATCHES, matches, 0) == 0) {
int start = offset + matches[0].rm_so;
int end = offset + matches[0].rm_eo;
offset += end;
// extract the matched substring
char substring[end - start + 1];
strncpy(substring, buffer + start, end - start);
substring[end - start] = '\0';
// split the substring into key and value
char *key = strtok(substring, "=");
char *value = strtok(NULL, "=");
// print the key and value
printf("%s: %s\n", key, value);
// extract pid and vid from the PRODUCT line
if (strcmp(key, "PRODUCT") == 0) {
unsigned int pid, vid;
if (sscanf(value, "%x/%x/%*x", &vid, &pid) == 2) {
printf("pid: %04x, vid: %04x\n", pid, vid);
}
}
}
// cleanup
regfree(®ex);
return 0;
}
```
输出结果为:
```
ACTION: remove
DEVPATH: /devices/pci0000:00/0000:00:08.1/0000:09:00.3/usb3/3-3/3-3.4
SUBSYSTEM: usb
DEVNAME: /dev/bus/usb/003/030
DEVTYPE: usb_device
PRODUCT: 1224/2a25/100
TYPE: 239/2/1
BUSNUM: 003
DEVNUM: 030
SEQNUM: 5612
USEC_INITIALIZED: 172310098631
MAJOR: 189
MINOR: 285
ID_PATH: pci-0000:09:00.3-usb-0:3.4
ID_PATH_TAG: pci-0000_09_00_3-usb-0_3_4
pid: 0025, vid: 1224
```