如果不使用libudev库,您也可以通过使用Linux系统提供的/sys文件系统来获取插入的USB设备信息。
以下是一个简单的示例代码,演示了如何在Linux下使用C++获取插入的USB设备信息(不使用libudev):
#include <iostream>
#include <fstream>
#include <string>
// 获取USB设备路径
std::string getUSBDevicePath() {
std::string path;
std::ifstream file("/proc/mounts");
if (file.is_open()) {
std::string line;
while (std::getline(file, line)) {
if (line.find("/dev/sd") != std::string::npos) {
size_t start = line.find("/dev/");
size_t end = line.find(" ", start);
path = line.substr(start, end - start);
break;
}
}
file.close();
}
return path;
}
// 获取USB设备信息
void getUSBDeviceInfo(const std::string& devicePath) {
std::ifstream file(devicePath + "/device/uevent");
if (file.is_open()) {
std::string line;
while (std::getline(file, line)) {
if (line.find("ID_VENDOR_ID=") != std::string::npos) {
size_t pos = line.find("=");
std::string vendorID = line.substr(pos + 1);
std::cout << "Vendor ID: " << vendorID << std::endl;
} else if (line.find("ID_MODEL_ID=") != std::string::npos) {
size_t pos = line.find("=");
std::string productID = line.substr(pos + 1);
std::cout << "Product ID: " << productID << std::endl;
}
}
file.close();
}
}
int main() {
std::string usbDevicePath = getUSBDevicePath();
if (!usbDevicePath.empty()) {
std::cout << "USB Device Path: " << usbDevicePath << std::endl;
getUSBDeviceInfo(usbDevicePath);
} else {
std::cout << "No USB device found" << std::endl;
}
return 0;
}
该代码通过解析/sys文件系统中的相关信息,获取插入的USB设备路径,并从相应路径下的uevent文件中获取设备的厂商ID和产品ID等信息。
请注意,这只是一个简单示例,您可以根据自己的需求进行扩展和修改。另外,请确保您有足够的权限运行该程序以读取/sys文件系统中的信息。<br/><br/><br/><p style="color:#CCCCCC;font-size:12px;">内容由零声教学AI助手提供,问题来源于学员提问</p> |