内核技术中文网»首页 论坛 圈点 查看内容

0 评论

0 收藏

分享

不使用libudev

如果不使用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>

回复

举报 使用道具

全部回复
暂无回帖,快来参与回复吧
主题 6339
回复 0
粉丝 0
扫码获取每晚技术直播链接
快速回复 返回顶部 返回列表