gpt4 book ai didi

c++ - 根据USB VID :PID in Linux获取设备路径

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

如果我插入一个设备,比如 /dev/ttyUSB0,我想根据它的 VID:PID(通过 lsusb 找到)得到数字 0 ),我怎么能在 C++ Linux 中做到这一点?我有这段代码可以找到一台打印机设备,如果它有帮助的话:

int printer_open (void)
{
char printer_location[] = "/dev/usb/lpX";
struct stat buf;

// continuously try all numbers until stat returns true for the connected printer
for (int i = 0; i < 10; i++)
{
printer_location[11] = '0' + i;
if (!stat (printer_location, &buf))
break;
}

return 0;
}

最佳答案

你可以使用libusb
apt-get install build-essential libudev-dev
这是一个很好的例子:
http://www.dreamincode.net/forums/topic/148707-introduction-to-using-libusb-10/
这是库描述:
http://libusb.sourceforge.net/api-1.0/

int main() {
libusb_context *context = NULL;
libusb_device **list = NULL;
int rc = 0;
ssize_t count = 0;

rc = libusb_init(&context);
assert(rc == 0);

count = libusb_get_device_list(context, &list);
assert(count > 0);

for (size_t idx = 0; idx < count; ++idx) {
libusb_device *device = list[idx];
libusb_device_descriptor desc = {0};

rc = libusb_get_device_descriptor(device, &desc);
assert(rc == 0);

printf("Vendor:Device = %04x:%04x\n", desc.idVendor, desc.idProduct);
}
}

如果您编译代码,请不要忘记添加库引用 -I/usr/include/libusb-1.0/- lusb-1.0

关于c++ - 根据USB VID :PID in Linux获取设备路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37417618/

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